如何在Java中将字符串块转换为数组中的元素
我使用此代码读取input.txt文件并将其存储到名为everything的字符串中。 这是我的input.txt 1 2 10 I 3 1 11 C 1 2 19 R 1 2 21 C 1 125 C 如果我想将字符串转换为包含整数和字母的数组,我应该使用什么方法 我尝试使用打印第一行的整数10:如何在Java中将字符串块转换为数组中的元素,java,Java,我使用此代码读取input.txt文件并将其存储到名为everything的字符串中。 这是我的input.txt 1 2 10 I 3 1 11 C 1 2 19 R 1 2 21 C 1 125 C 如果我想将字符串转换为包含整数和字母的数组,我应该使用什么方法 我尝试使用打印第一行的整数10: String file_path = "src/input.txt"; String everything; BufferedReader br = new BufferedRead
String file_path = "src/input.txt";
String everything;
BufferedReader br = new BufferedReader(new FileReader(file_path));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
} finally {
br.close();
}
但是它不起作用。试试这个
如果您使用的是jdk8
到字符数组
char arry[];
arry=everything.toCharArray();
System.out.print(arry[4]);
到字符串数组
public static void readLines() {
String file_path = "src/input.txt";
ArrayList<String> lines = new ArrayList<>();
try {
try (Stream<String> stream = Files.lines(Paths.get(file_path))) {
stream.forEach(lines::add);
}
} catch (IOException e) {
e.printStackTrace();
}
String everything = "";
for (int i = 0; i < lines.size(); i++) {
if(lines.get(i).length()>0){ // uncomment if you don not want to remove empty lines
everything = everything + lines.get(i);
}
}
char[] chars = everything.toCharArray();
for (int i = 0; i <chars.length ; i++) {
System.out.println("Char at index "+i+"; "+ chars[i]);
}
}
老路
public static void readLines() {
String file_path = "src/input.txt";
ArrayList<String> lines = new ArrayList<>();
try {
try (Stream<String> stream = Files.lines(Paths.get(file_path))) {
stream.forEach(lines::add);
}
} catch (IOException e) {
e.printStackTrace();
}
String[] everything = new String[lines.size()];
for (int i = 0; i < lines.size(); i++) {
everything[i] = lines.get(i);
}
}
为什么不使用字符串ArrayList?你的概念是零。首先尝试阅读一些关于字节和字符的资料。没有必要直接从stackoverflow获得答案。您的代码并不是解决问题的认真尝试。让我们看看你的合理尝试。
public static void readFile() {
ArrayList<String> allStrings = new ArrayList<>();
String file_path = "src/input.txt";
String everything;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file_path));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line.length() > 0) {
allStrings.add(line);
}
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
//Convert to array
String[] everyString = new String[allStrings.size()];
System.out.println("Everything: " + everything);
for (int i = 0; i < allStrings.size(); i++) {
everyString[i] = allStrings.get(i);
}
//Print Array
for (int i = 0; i < allStrings.size(); i++) {
System.out.println("Index: " + everyString[i]);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}