Java用分支结构循环编译这道题怎么做?满意有重赏

例题:接收或赋值两个字符串,统计第二个字符串(长度>=2)在第一个字符串(长度>=10)里出现的次数,另外统计第二个字符串中每个字符在第一个字符串中出来的次数。(提示:字符串的常见方法)
String strone=”run Hello World code. This is my java code”;
String strtwo=“code”;
strtwo在strone中出现了2次
strtwo 中的每个字符:“c”在strone中出现了2次,”0”在strone中出现了4次, ”d”在strone中出现了3次,”e”在strone中出现了3次。
麻烦给出源代码和注释

public class Demo {
public static void main(String[] args) {
String strone = "run Hello World code. This is my java code";
String strtwo = "code";
int count = strone.split(strtwo).length; // 用字符串2去拆分字符串1,拆分后得到的数组长度-1就是字符串2在字符串1中出现的次数
System.out.println("strtwo在strone中出现了" + count + "次");
System.out.print("strtwo 中的每个字符: ");
for (char cInStr2 : strtwo.toCharArray()) {
// 遍历strtwo中的每一个字符, 声明变量记录当前字符在strone中出现的次数
int charCount = 0;
for (char cInStr1 : strone.toCharArray()) {
// 比较当前字符和strone中的每个字符,如果相同,当前字符出现的次数就+1
charCount += cInStr1 == cInStr2 ? 1 : 0;
}
System.out.print("\"" + cInStr2 + "\"在strone中出现了" + charCount + "次,");
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-04-14
import java.util.regex.Matcher;

import java.util.regex.Pattern;

/**

* @Auther: liyue

* @Date: 2020/4/14 15:12

* @Description:

*/

public class Test2 {

public static void main(String[] args) {

/**

* 例题:接收或赋值两个字符串,统计第二个字符串(长度>=2)在第一个字符串(长度>=10)里出现的次数,另外统计第二个字符串中每个字符在第一个字符串中出来的次数。(提示:字符串的常见方法)

* String strone=”run Hello World code. This is my java code”;

* String strtwo=“code”;

* strtwo在strone中出现了2次

* strtwo 中的每个字符:“c”在strone中出现了2次,”0”在strone中出现了4次, ”d”在strone中出现了3次,”e”在strone中出现了3次。

*/

String strone = "run Hello World code. This is my java code";

String strtwo = "code";

// 定义正则表达式

Pattern pattern = Pattern.compile(strtwo);

Matcher matcher = pattern.matcher(strone);

int count1 = 0;

while (matcher.find()) {

// 每查到一个计数加1

count1++;

}

System.out.println("字符串\"" + strtwo + "\"在字符串\"" + strone + "\"中出现了" + count1 + "次;");

System.out.println();

String[] strings = strtwo.split("");

for (String aChar : strings) {

pattern = Pattern.compile(aChar);

matcher = pattern.matcher(strtwo);

int count2 = 0;

while (matcher.find()) {

count2++;

}

System.out.println("字符\"" + aChar + "\"在字符串\"" + strone + "\"中出现了" + count2 + "次;");

}

}

}本回答被网友采纳
第2个回答  2020-04-22
public static void main(String[] args) {
String strone="run Hello World code. This is my java code";
String strtwo="code";
System.out.println("strtwo在strone中出现了"+StringUtils.countMatches(strone,strtwo)+"次");

/*把字符串转为char字符数组并遍历*/
for(char string :strtwo.toCharArray()){
/*没错,StringUtils中有这个方法,参数1值是被查询的字符串,参数2值是要查询的字符串*/
System.out.println(string+"在strone中存在的次数:"+StringUtils.countMatches(strone,string));
}
}
第3个回答  2020-04-17

相似回答