如何用java求一个字符串在另一个字符串中出现的位置?

来源:百度知道 编辑:UC知道 时间:2024/07/06 23:53:49
输入任意一个字符串!输入在上一个字符串中的一个或一组字或词!计算这个字或词在输入的那个字符串中出现了几次!

import java.util.*;

public class CountChars {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Please Input Your String!");
String str = sc.nextLine();
Map<Character, Integer> map = countLetters(str);
System.out.println("total kinds: " + map.size());

for (Map.Entry<Character, Integer> entry : map.entrySet()) { //增强的for循环
System.out.printf("letter %c: %d\n", entry.getKey(), entry.getValue());
}
}

static Map<Character, Integer> countLetters(String s) {
if (s == null) {
return null;
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
char c;
Integer oldValue;
int newValue;
for (int i = 0; i < s.length(); ++i) {
c = s.charAt(i);
oldValue = map.get(c);