简体   繁体   中英

Returning substring of string after first occurence of a comma

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.

你可以做:

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

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];

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$

尝试使用String.indexOf(“,”)等。

You can use the overloaded split method which allows to define a limit of substrings.

split(",",1)

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