1.已知字符串:"this is a test of java".按要求执行以下操作:(要求源代码、结果截图。)
① 统计该字符串中字母s出现的次数。
② 统计该字符串中子串“is”出现的次数。
③ 统计该字符串中单词“is”出现的次数。
④ 实现该字符串的倒序输出
(1)
packagedemo;public classtext {public static voidmain(String[] args) {//TODO Auto-generated method stub
String str = "this is a test of java";int sum = str.replaceAll("[^s]", "").length();
System.out.println(sum);
}
}
(2)
packagedemo;public classtext {public static voidmain(String[] args) {//TODO Auto-generated method stub
String str = "this is a test of java";
String s= "is";
String[] arr= (","+str.toLowerCase()+",").split(s);
System.out.println(arr.length- 1);
}
}
(3)
packagedemo;importjava.util.HashMap;public classdemo1 {public static voidmain(String[] args) {
String str= "this is a test of java";
String[] array= str.split(" ");
HashMap map = new HashMap();for(String ss : array) {if(map.containsKey(ss)) {
map.put(ss, map.get(ss)+ 1);
}else{
map.put(ss,1);
}
}
System.out.println(map);
}
}
(4)
packagedemo;public classtext {public static voidmain(String[] args) {//TODO Auto-generated method stub
String str = "this is a test of java";
StringBuffer s= newStringBuffer(str);
System.out.println(s.reverse().toString());
StringBuffer sb2= newStringBuffer();for (int i = str.length()-1; i >=0; i--) {
s.append(str.charAt(i));
}
System.out.println(sb2);
}
}
2.请编写一个程序,使用下述算法加密或解密用户输入的英文字串。要求源代码、结果截图。
代码
packagedemo;public classdemo1 {public static voidmain(String[] args) {
String str= "20188492";
System.out.println(demo1.moveToRight(str,3));
}private static String moveToRight(String str,intposition) {
String str1=str.substring(str.length()-position);
String str2=str.substring(0, str.length()-position);return str1+str2;
}
}
但是考虑到密码是手动输入,做了一下更改
packagedemo;importjava.util.Scanner;public classdemo1 {public static voidmain(String[] args) {
System.out.println("请输入密码:");
Scanner sca=newScanner(System.in);
String str=sca.next();
System.out.println(demo1.moveToRight(str,3));
}private static String moveToRight(String str,intposition) {
String str1=str.substring(str.length()-position);
String str2=str.substring(0, str.length()-position);return str1+str2;
}
}
3.已知字符串“ddejidsEFALDFfnef2357 3ed”。输出字符串里的大写字母数,小写英文字母数,非英文字母数。
代码
packagedemo;public classdemo1 {public static voidmain(String[] args) {
String s= "ddejidsEFALDFfnef2357 3ed";int capital = 0;int lowercase = 0;int numberCount = 0;for (int i = 0; i < s.length(); i++) {char ch =s.charAt(i);if (ch >= 'a' && ch <= 'z') {
lowercase++;
}else if (ch >= 'A' && ch <= 'Z') {
capital++;
}else if (ch >= '0' && ch <= '9') {
numberCount++;
}
}
System.out.println("大写字母" + capital + "个");
System.out.println("小写字母" + lowercase + "个");
System.out.println("数字" + numberCount + "个");
}
}