繁体   English   中英

用两个不同的分隔符分割字符串

[英]Split a string by two different delimiters

我有这个字符串。

One@two.three

我想找到三个不同的部分( 忽略@

过去使用indexOf('@')来查找它,我不确定下一步该怎么做。 我还能使用诸如indexOf()类的其他东西吗?

我还能使用诸如indexOf()之类的其他东西吗?

您需要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);

使用split()

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

版画

One
two
three

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM