简体   繁体   中英

JAVA-How to split string to int array based on spaces

I have multiple line input where each line is line of matrix. I save this line as string and after that i want to split this string based on spaces, but due to better readability the number of spaces between number is not defined. So when i want to parse to int afterwards, it throws an error because, on some places there are more than one space. Is there any solution how i could fix that problem? Thanks

Here is my code, how i tried to solved that

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
int[][] matrix=new int[n][n];
String[] temp;
for (int row = 0; row < n; row++) {
    line =br.readLine();
    temp = line.split("\\s+");
    for(int i=0;i<n;i++){
    matrix[i][row]=Integer.parseInt(temp[i]);
}

here is examplary input

10 10  0 10  5
 5 20 10  7 12
 1  2  3  5  9
10 15 20 35  2
 2 15  5 15  2

The issue is when you have spaces in the beginning of the String:

"10 10  0 10  5".split("\\s+"); // ["10", "10", "0", "10", "5"]
" 5 20 10  7 12".split("\\s+"); // ["", "5", "20", "10", "7", "12"]

So then you get an extra empty String. Adding an extra trim() should help:

line.trim().split("\\s+");

Just replace multiple spaces with single spaces

see Java how to replace 2 or more spaces with single space in string and delete leading spaces only

And after that just do the splitting as you would normaly do.

If you write the logic portion correctly, you can use your space as the delimiter and also excuse the extra space with if/then statements (test for isWhitespace, or isDigit).

Honestly, you can just use isDigit to verify the item at position [i] is in fact a digit, and just store this data in your string.

I wont write the code for you but there are a ton of workarounds for this problem... and the problem is all in your definitions of what gets stored in your String, really.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM