繁体   English   中英

如何使用Java在String中查找字符的出现?

[英]How to find a occurrence of a character in String using java?

我有一个字符串,并且想将其子字符串替换为“,”的第3次出现。 我可以使用数组来实现。 这是代码

String test ="hi,this,is,a,string.";
String[] testArray = test.split(",");
System.out.println(testArray[0]+","+testArray[1]+","+testArray[2]);

输出是:- hi,this,is

无论如何,有没有使用“ substring(0,text.indexOf(“,”))“方法实现相同的功能。第二件事是在某些情况下字符串中没有”,“并且我想处理两种情况

提前致谢

我不确定我是否真的建议这样做,但是-是的; indexOf两个参数的重载 ,可让您指定要搜索的起始位置; 所以你可以这样写:

final int firstCommaIndex = test.indexOf(',');
final int secondCommaIndex = test.indexOf(',', firstCommaIndex + 1);
final int thirdCommaIndex = test.indexOf(',', secondCommaIndex + 1);
System.out.println(test.substring(0, thirdCommaIndex));

因此,您所寻找的基本上是一种在String中接收char(,)的第n(3rd)个索引的方法。 尽管Java的标准库中没有该功能,但是您可以创建自己的构造(看起来像这个答案 ),

或者,您也可以使用Apache的StringUtils ,使所需的解决方案看起来像这样:

String test ="hi,this,is,a,string.";
int index = StringUtils.ordinalIndexOf(test, ",", 3);
String desired = test.substring(0, index);
System.out.println(desired);

您可以使用正则表达式来实现此目的:

import java.util.regex.*;

public class TestRegex {
    public static void main(String []args){
        String test = "hi,this,is,a,string.";

        String regex = "([[^,].]+,?){3}(?=,)";

        Pattern re = Pattern.compile(regex);

        Matcher m = re.matcher(test);
        if (m.find()) {
            System.out.println(m.group(0));
        }
     }
}

使用流Java 8的其他方法。这可以处理您的两种情况

System.out.println(Stream.of(test.split(",")).limit(3).collect(Collectors.joining(",")));

暂无
暂无

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

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