1. 输入两个字符串str1、str2,统计字符串str2出现在str1中的次数。
如:str1=”aaas lkaaas” ,str2=” as” ,则应输出 2
提示:文本输入
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in); //定义扫描键盘输入的对象
String s = sc.nextLine(); //从键盘读入一行文本
...
sc.close();
}
package 实验七;
import java.util.Scanner;
public class 实验七1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
int sum=0;
System.out.println("请输入第一个字符串:");
String str1=input.nextLine();
System.out.println("请输入第二个字符串:");
String str2=input.nextLine();
int lo=str1.indexOf(str2);
while(lo!=-1) {
sum++;
lo=str1.indexOf(str2,lo+1);
}
System.out.println("第二个字符串在第一个字符串中出现了"+sum+"次!");
}
}
2. 从键盘输入一串字符,输出有多少个不同的字符、每个字符出现的次数。
package 实验七;
import java.util.Scanner;
public class 实验七2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("输入一行字符串!");
Scanner input =new Scanner(System.in);
String str=input.nextLine();
StringBuffer k=new StringBuffer(str);
int length=k.length();
System.out.println("共有"+length+"个字母!");
String a;
int index,sum;
for(int i=0;i<k.length();) {
sum=0;
a=k.substring(0,1);
index=k.indexOf(a);
while(index!=-1) {
sum++;
k.deleteCharAt(index);
index=k.indexOf(a,index);
}
System.out.println(a+"字母有"+sum+"个");
}
}
}