- 实验目的
- 掌握类String类的使用;
- 学会使用JDK帮助文档;
- 实验内容
1.已知字符串:"this is a test of java".按要求执行以下操作:(要求源代码、结果截图。)
- 统计该字符串中字母s出现的次数。
- 统计该字符串中子串“is”出现的次数。
- 统计该字符串中单词“is”出现的次数。
- 实现该字符串的倒序输出。
实验代码
public static void main(String[] args) { String s = "this is a test of java"; int n = (s.split("s")).length - 1; System.out.println("s出现的次数"+n); int p = (s.split("is")).length - 1; System.out.println("子串is出现的次数"+p); int count=0; char[]a=s.toCharArray(); for(int i=0;i<a.length;i++) { if(a[i]=='i') { if(a[i+1]=='s'&&a[i-1]==' ') { count++; } } } System.out.println("单词is出现的次数"+count); StringBuffer s1 = new StringBuffer(s).reverse(); System.out.println("倒序结果" + s1); }
结果截图
2.请编写一个程序,使用下述算法加密或解密用户输入的英文字串。要求源代码、结果截图。
源代码
import java.util.Scanner; public class tainanle { public static void main(String[] args) { Scanner z=new Scanner(System.in); System.out.println("请输入要加密的字符串"); String a=z.nextLine(); char[]b=a.toCharArray(); int x=0,c = 4; int j=b.length-1; char t; for(x=0,j=b.length-1;x<j;x++,j--) { t=b[x]; b[x]=b[j]; b[j]= t; } for(x=0,j=c-1;x<j;x++,j--) { t=b[x]; b[x]=b[j]; b[j]= t; } for(x=c,j=b.length-1;x<j;x++,j--) { t=b[x]; b[x]=b[j]; b[j]= t; } System.out.println(String.valueOf(b)); } }
结果截图
3.已知字符串“ddejidsEFALDFfnef2357 3ed”。输出字符串里的大写字母数,小写英文字母数,非英文字母数。
源代码
public static void main(String[] args) { String s="ddejidsEFALDFfnef2357 3ed"; char[]a=s.toCharArray(); int q=0; int w=0; int e=0; for(int i=0;i<a.length;i++) { if(a[i]>='A'&&a[i]<='Z') { q++; } else if(a[i]>='a'&&a[i]<='z') { w++; } else { e++; } } System.out.println("大写字母数为:"+q); System.out.println("小写字母数为:"+w); System.out.println("非英文字母数为:"+e); }
结果截图
总结
这周学了string类型,基本掌握了书上12种string类型的使用方法。在作业过程中还可以使用一些快捷方法,刚开始不知道,上网查了才知道,比如那个倒序的。