Data structure - basic operation and pattern matching of strings

1. Count the number of occurrences of characters in a string

2. Methods and steps

Use the indexof(str, fromindex) method of String to loop through and add a counter to count the number of times.

3. The original record of the experiment

public class CountTimes{

public static void main(String[] args)

{

String str= "Each country has its own national anthem";

int times = searchstr ("country", str); //return 3

System.out.println(times);

}

public static int searchstr(String key, String str)

{

int index = 0;//The searched subscript each time

int count = 0;//counter

while (( index=str.indexOf(key, index)) != -1)

{

index = index + key.length();

count++;

}

return count;

}

}

Five. Results

"Nation" appears three times in "Each country has its own national anthem"

Guess you like

Origin blog.csdn.net/weixin_45823684/article/details/128536663