简体   繁体   中英

Split a string by two different delimiters

I have this string.

One@two.three

I want to find the three different parts ( ignoring @ )

Past using indexOf('@') to find it, I'm not sure what to do next. What other things like indexOf() could I use?

What other things like indexOf() could I use?

You need indexOf

 String text = "One@two.three";
 int pos1 = text.indexOf('@');
 // search for the first `.` after the `@`
 int pos2 = text.indexOf('.', pos1 + 1);

 if (pos1 < 0 || pos2 < 0)
    throw new IllegalArgumentException();


 String s1 = text.substring(0, pos1);
 String s2 = text.substring(pos1 + 1, pos2);
 String s3 = text.substring(pos2 + 1);

Use split() :

final String input = "One@two.three";
for (String field: input.split("@|\\.")) {
    System.out.println(field);  
}

Prints :

One
two
three

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