Search code examples
javastringsubstring

Finding the last character of of a line in a String


I have a program that reads the content of a file and puts it as a String. The String input looks like this:

Age: 0-11,25203,18,54% ~
Age: 12-19,26722,35,68% ~
Age: 20-39,28427,46,72%. ~
Note: Each ICU admission is also included in the total number of hospitalization.,,, ~

Where each "~" is a line skip.

I am looking to put each of the Age lines in a String array. I managed to find the number of '\n' in my String that I put into counter. So, I tried to do

for(int i=0; i<counter;i++){
array[i]=input.substring(0, input.indexOf("\n")); //Puts the first line of the String in the array
input=input.replaceFirst(array[i],""); //To remove the first line of the String

But this doesn't work as the String won't cut further than the second line. Therefore, "~" is not equal to '\n' as I cannot find a '\n' once my String is chopped to

Age: 12-19,26722,35,68% ~
Age: 20-39,28427,46,72%. ~
Note: Each ICU admission is also included in the total number of hospitalization.,,, ~

Also, I found this strange behaviour once the String was chopped:

System.out.println("A: "+input.contains("\n"));
System.out.println("B "+input.indexOf('\n'));

Which renders the output:

A: true
B: 0

And so, I am confused because "\n" should be at the end of my line and not at index 0. As such, I think I can't chop my string further because it locates the "\n" at 0.

Quick note: I am not allowed to find the exact number of characters in the line and chop it after since it's only a sample file and the length of the line could vary.


Solution

  • substring's second argument is the end of the substring, exclusively. substring(a,b) get you the substring from index a to index b-1.

    Example:

    "abcd".substring(0,1) -> "a"
    "abcd".substring(1,3) -> "bc"
    

    Which means for your example, you are cutting everything away except the newline, so the second time your loop runs, input has a newline as the first character. You get indexOf('\n') = 0, nothing happens.

    To include the newline in array[i], you have to do

    array[i]=input.substring(0, input.indexOf("\n") + 1);