Java day09 String(1)

本文介绍了一种自定义字符串处理方法,包括去除两端空格、字符串反转及查找子串出现次数等功能。通过实例演示了如何利用Java实现这些实用的操作。

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

/*实现 去除字符串两端的空格 charAt(index)_获取下标对应字符
						substring(begin,end) 获取子序列

实现 字符串反转  toCharArray 字符串转字符数组
				字符串对象初始化方式之一 其构造函数可带数组类型参数
实现 得到A串在B串中出现的次数  b.indexOf(a,bgein) 返回a串在b串(自begin下标开始的)中的首次出现的下标
*/

class StringTest
{
	String s;
	StringTest(String s)
	{
		this.s=s;
	}
	public String myTrim()
	{//返回字符串去除两端空格后的部分
		int begin=0;
		int end=s.length()-1;
		//首
		while(begin<=end&&s.charAt(begin)==' ')
		{//注意!!!begin<=end&&s.charAt(begin)==' '和 s.charAt(begin)==" "&&begin<=end 是有区别的
			//这告诉我们,先判断大前提,再判断小前提
			begin++;
		}
		if(begin>end)
			return "空格字符串";
		//尾
		while(begin<=end&&s.charAt(end)==' ')
		{
			end--;
		}
		end++;		
		//返回 begin 到end-1 下标所指示的子序列
		return s.substring(begin,end);
	}
	public String reverseString(String s)
	{
		//字符串变字符数组
		char []ch=s.toCharArray();
		//反转数组
		reverse(ch);
		//数组变回字符串
		return new String(ch);
	}
	public void reverse(char []arr)
	{
		for(int start=0,end=arr.length-1;start<end;start++,end--)
		{
			swap(arr,start,end);
		}
	}
	public void swap(char[]arr,int a,int b)
	{
		arr[a]=(char)(arr[a]^arr[b]);
		arr[b]=(char)(arr[a]^arr[b]);
		arr[a]=(char)(arr[a]^arr[b]);
	}
	
}
class StringTestDemo
{	public static int getSubCount(String s,String key)
	{//输出子串在母串中的数目
		int index=0;
		int count=0;
		while((index=s.indexOf(key,index))!=-1)	
		{	
			count++;
			//1
		//	s=s.substring(index+key.length());
			//2
			index+=key.length();
			
		}
		return count;
	}
	public static void main(String[] args) 
	{
		StringTest st=new StringTest("1234512   ");
		String s1=st.myTrim();
		System.out.println(s1);
		System.out.println(st.reverseString(s1));
		System.out.println(getSubCount(s1,"12"));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值