Returning substring of string after first occurence of a comma

11,667

Solution 1

You can do:

line.substring(line.indexOf(",")+1)

Solution 2

There are a couple of different ways of removing everything before the first occurrence of a ,.

  1. Find the index (position) of the first , and substring using that index.

This would look like

String wantedPart = lineOfText.substring(lineOfText.indexOf(",") + 1);

Since indexOf returns the index of the , itself, you need to add one to get everything past it.


  1. Use a better overload like String.split(String regex, int limit). This overload allows you to match a maximum of limit substrings. So with a limit of 2, it will split on the first , found (and no more).

In your code, you could use

String wantedPart = lineOfText.split(",")[1];

Solution 3

If a shell script will do, you can use the cut command:

-d ',' means use a comma as -f2- means use fields 2 onwards.

Machine:~ donald$ cat file.txt
0,1
1,2
3,4
5,6,7
8,10
9,10
Machine:~ donald$ cat file.txt | cut -d ',' -f2-
1
2
4
6,7
10
10
Machine:~ donald$
Share:
11,667
Limone_77
Author by

Limone_77

Updated on June 14, 2022

Comments

  • Limone_77
    Limone_77 almost 2 years

    How can I take this input CSV file:

    0,1
    1,2
    3,4
    5,6,7
    8,10
    9,10
    

    and return only the substring of each line after the first occurrence of "," so that my output is:

    1
    2
    4
    6,7
    10
    10
    

    I can only figure out how to parse the string within a certain range after splitting by commas, so I am using string.split(",")[1] to return everything after the first comma and before the next comma but I can't figure out how to get everything after the first comma. So for the inputs with more than one comma, I'm missing data.