Kopite1905 :
So I have this string : "New York,USA,1000\n" + "City,World,2000\n";
I need to split it first by newline and then by comma, so at the end I get an array of strings that is like this: New York has index 0, USA index 1, 1000 index 2, World index 4 and so on..I tried using
String[] newline = string.split("\n")
and then declaring a new array of strings called result ( giving it 1000 characters randomly ) and making a for loop like this:
String[] result = new String[1000];
for (String s : newline){
result=s.split(",");
}
But it doesn't work properly. Any help, please?
xuxianyuan :
public class Test {
public static void main(String[] args) {
String string = "New York,USA,1000\n" + "City,World,2000\n";
String[] newline = string.split("\n");
String[] result = new String[1000];
//first loop
result = newline[0].split(",");
System.out.println(Arrays.toString(result));
//second loop
result = newline[1].split(",");
System.out.println(Arrays.toString(result));
}
}
/*
output:
[New York, USA, 1000]
[City, World, 2000]
*/
result would be overrided instead of append.
public class Test {
public static void main(String[] args) {
String string = "New York,USA,1000\n" + "City,World,2000\n";
String[] newline = string.split("\n");
String[] result = new String[1000];
int index = 0;
for (String s : newline) {
for (String t : s.split(",")) {
result[index++] = t;
}
}
for (int i = 0; i < index; i++) {
System.out.print(result[i] + " ");
}
}
}
/*
output:
New York USA 1000 City World 2000
*/
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=403397&siteId=1