Java实验 常用实用类

本文介绍了如何在Java中使用String类进行字符串操作,包括判断字符串相等、前缀后缀匹配、字典序比较、检索子串、创建新字符串以及将数字型字符串转换为整数。还演示了如何实现字符串查找功能,统计短字符串在长字符串中的出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实验目的

掌握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 + "次");
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值