Occurrences of substring in a string

后端 未结 24 2170
眼角桃花
眼角桃花 2020-11-22 03:35

Why is the following algorithm not halting for me? (str is the string I am searching in, findStr is the string I am trying to find)

String str = \"helloslkhe         


        
24条回答
  •  独厮守ぢ
    2020-11-22 03:43

    Try this one. It replaces all the matches with a -.

    String str = "helloslkhellodjladfjhello";
    String findStr = "hello";
    int numberOfMatches = 0;
    while (str.contains(findStr)){
        str = str.replaceFirst(findStr, "-");
        numberOfMatches++;
    }
    

    And if you don't want to destroy your str you can create a new string with the same content:

    String str = "helloslkhellodjladfjhello";
    String strDestroy = str;
    String findStr = "hello";
    int numberOfMatches = 0;
    while (strDestroy.contains(findStr)){
        strDestroy = strDestroy.replaceFirst(findStr, "-");
        numberOfMatches++;
    }
    

    After executing this block these will be your values:

    str = "helloslkhellodjladfjhello"
    strDestroy = "-slk-djladfj-"
    findStr = "hello"
    numberOfMatches = 3
    

提交回复
热议问题