Record the number of times a substring appears in the entire string (JAVA)

Record the number of occurrences of a substring in the entire string (Java)

1. Task description
Write a program to record the number of occurrences of a substring in the entire string. For example, record the number of occurrences of the substring "nba" in the entire string "nbaernbatnbaynbauinbaopnba". Observe that the number of substrings "nba" appears 6. It is required to use the common methods of the String class to calculate the number of occurrences.
2. Operation result
Insert picture description here
3. Implementation idea

  1. The main string string and the pattern string string2, using the string.IndexOf (String2) method to get the position where the first pattern string appears are stored in the address variable.
  2. Set up the while loop, taking the address where it appears + the length of the pattern string as the starting position of the next loop. Use the return value of the string.IndexOf (string2, address + string2.lenght) method as the judgment condition, and record the number of times the pattern string appears in the main string.
    [String.IndexOf (parameter one, parameter two) parameter one: mode string, parameter two: starting position]
    4. Implementation code
    Insert picture description here
Published 5 original articles · Likes6 · Visits 29

Guess you like

Origin blog.csdn.net/weixin_44781355/article/details/105458109