我正在尝试将扫描仪复制到字符串中,然后精确返回该字符串,然后在新字符串的末尾添加新行。因此等于This \ nis a \ ntest的扫描仪将返回一个等于This \ nis a \ ntest \ n的字符串。
到目前为止我的代码
public static String scannerToString (Scanner scnr)
{
String string = "";
while (scnr.hasNextLine())
{
string = scnr.nextLine();
}
return string + "\\n";
}
我改用StringBuilder解决了这个问题。 这是我的新代码。
StringBuilder result = new StringBuilder();
while (scnr.hasNextLine())
{
String string = scnr.nextLine();
result.append(string + "\n");
}
return result.toString();
答案 0 :(得分:0)
根据搜索,这是Olathe's String
inspection method转换为使用StringBuilder
和lucasvc's Scanner
contents retriever的组合:
import java.util.Scanner;
public class InspectScanner {
public static String inspect(final String str) {
StringBuilder result = new StringBuilder("\"");
for (int i = 0; i < str.length(); i++) {
final char ch = str.charAt(i);
if (ch >= 128) result.append(String.format("\\u%04x", (int) ch));
else if (ch == '"') result.append("\\\"");
else if (ch >= 32) result.append(ch);
else switch (ch) {
case '\b': result.append("\\b"); break;
case '\f': result.append("\\f"); break;
case '\n': result.append("\\n"); break;
case '\r': result.append("\\r"); break;
case '\t': result.append("\\t"); break;
default: final int iNext = i + 1;
if (iNext == str.length())
result.append(String.format("\\%o", (int) ch));
else {
final char nextCh = str.charAt(iNext);
result.append(String.format((nextCh >= '0' && nextCh <= '9') ? "\\%03o" : "\\%o", (int) ch));
}
}
}
result.append("\"");
return result.toString();
}
public static String getRemainingScannerContents(final Scanner scanner) {
scanner.useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
public static final void main(final String[] args) {
Scanner scanner = new Scanner("test\ntest\n12345");
System.out.println(inspect(getRemainingScannerContents(scanner)));
}
}
"test\ntest\n12345"