After reading text file that contain words and numbers, I split it into words and numbers and left with blank lines in both splited words and numbers.
I try to remove the blank lines but the code did'nt work. Someone can help
String textfile = read.next();
String[] words = textfile.split("\\d");
String[] numbers = textfile.split("[^0-9]");
StringBuffer splitedwords = new StringBuffer();
StringBuffer splitednumbers = new StringBuffer();
for(int k = 0; k<numbers.length; k )
{
splitednumbers.append(numbers[k]);
String remove_blank_lines_of_splitednumbers = splitednumbers.toString();
remove_blank_lines_of_splitednumbers.replaceAll("[\r\n]{2,}", "");
System.out.println(remove_blank_lines_of_splitednumbers);
}
Igot this output
13
46
16
08
96
11
150
200
379
I want the output to be
13
46
16
08
96
11
150
200
379
CodePudding user response:
If you need to remove white spaces, such as your empty lines, at the beginning or end of a String you can simply use the trim method instead of restorting to a replace with a regex.
If you'll aplly a trim on each numbers[k] in your for you should be able to remove every white characters around them.
splitednumbers.append(numbers[k].trim());
Or try still the replaceAll withe a regex matching white spaces.
splitednumbers.append(numbers[k].replaceAll("\\s ", ""));
CodePudding user response:
Maybe you should still try with a replaceAll but using the \s character class though. I don't think this code (replaceAll("[\r\n]{2,}", ""); can detect you new lines and carriage return the way you expect.