实验目的
掌握String类的常用方法。
实验内容
【1】题目:编写一个Java应用程序,判断两个字符串是否相同(注意==与equals的区别),判断字符串的前缀、后缀是否和某个字符串相同,按字典顺序比较两个字符串的大小关系,检索字符串,创建字符串,将数字型字符串转为数字。
package homework;
public class text1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
String n1 = new String("Hello world!");
String n2 = new String("Goodbye world!");
String n3 = new String("Hello world!");
System.out.println("字符串是否相同:"+ n1.equals(n2));
System.out.println("字符串是否相同:"+ n1.equals(n3));
String n4 = new String("天气预报:尼格台风登录广东沿海地区");
String n5 = new String("国际新闻;苏纳克当选英国总统");
System.out.println("字符串前缀是否相同:"+ n4.startsWith("天气"));
System.out.println("字符串前缀是否相同:"+ n5.startsWith("天气"));
System.out.println("字符串后缀是否相同:"+ n4.endsWith("总统"));
System.out.println("字符串后缀是否相同:"+ n5.endsWith("总统"));
String n6 = new String("weather");
String n7 = new String("cold");
System.out.println("按字典顺序比较两个字符串的大小关系:"+ n6.compareTo(n7));
System.out.println("检索字符串:"+ n6.contains("wea"));
System.out.println("创建字符串:"+ n4.substring(1,3));
String n8 = new String("1111");
int x = Integer.parseInt(n8);
System.out.println("将数字型字符串转为数字:"+ x);
}
}
【2】题目:编写一个Java应用程序,实现字符串查找功能。在键盘输入一个长字符串,再输入一个短字符串。统计短字符串在长字符串中出现的次数。效果如图:
package homework;
import java.util.Scanner;
public class text2 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.println("请输入原字符串:");
String st = sc.next();
System.out.println("请输入指定字符串:");
String M = sc.next();
way(st, M);
}
public static void way(String st, String M) {
int count = (st.length() - st.replace(M, "").length()) / M.length();
System.out.println("指定字符串在原来字符串中出现:" + count + "次");
}
}