62,621
社区成员
发帖
与我相关
我的任务
分享 public static void main(String[] args) {
String str = "abc\n\nd\n\nnghi";
char[] chars = str.toCharArray();
int index = 0;
for (char c : chars) {
if (c == '\n') {
index -= 1;
continue;
}
chars[index++] = c;
}
System.out.println(new String(chars, 0, index));
} public static void main(String[] args) {
String str = "abc\n\nd\n\nnghi";
List<Character> list = new ArrayList<>();
int index = 0;
for (char c : str.toCharArray()) {
if (c == '\n') {
index -= 1;
continue;
}
list.add(index++, c);
}
list.subList(0, index).forEach(System.out::print);
}public class EscapeApplication {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input the orginal string:");
String input = in.nextLine();
StringBuilder builder = reConstruct(handle(input));
System.out.println(builder.toString());
}
//合并分割处理后的数据
private static StringBuilder reConstruct(String[] datas) {
StringBuilder builder = new StringBuilder();
for (String data : datas) {
builder.append(data);
}
return builder;
}
//处理转义字符串
private static String[] handle(String input) {
boolean lasted = false;
if (input.endsWith("\\n")) {
lasted = true;
}
String[] datas = input.split("\\\\n");
for (int i = 0; i < datas.length; i++) {
if (datas[i].length() == 0) {
int backIndex = i - 1;
while (backIndex >= 0) {
String backStr = datas[backIndex];
if (backStr.length() > 0) {
datas[backIndex] = backStr.substring(0, backStr.length() - 1);
break;
}
backIndex--;
}
} else {
if (i != datas.length - 1)
datas[i] = datas[i].substring(0, datas[i].length() - 1);
else {
if (lasted)
datas[i] = datas[i].substring(0, datas[i].length() - 1);
}
}
}
return datas;
}
}