面向对象-字符串练习

1、去除字符串两端的空格

代码:

public class code
{
	public static String method_get(String str) {
		int start=0,end=str.length()-1;
		while(start<=end && str.charAt(start)==' ')
			start++;
		while(start<=end && str.charAt(end)==' ')
			end--;
		return str.substring(start, end+1);
	}
	
    public static void main(String[] args) {
    	String str1="   a b c ";
    	str1=method_get(str1);
    	sop(str1);
    }
    
    public static void sop(Object obj) {
		System.out.println(obj);
	}
}

2、字符串反转

代码:

public class code
{
	public static String method_get(String s,int start,int end) {
		char[] arr=s.toCharArray();
		reverse(arr,start,end);
		return new String(arr);
	}
	
	public static void reverse(char[] arr,int x,int y) {
		for(int start=x,end=y;start<end;start++,end--) {
			swap(arr,start,end);
		}
//		System.out.println(arr);
	}
	
	
    private static void swap(char[] arr, int x, int y) {
		char temp = arr[x];
		arr[x]=arr[y];
		arr[y]=temp;
//		System.out.println(temp);
		
	}

	public static void main(String[] args) {
    	String d=" evol ";
    	d=method_get(d,1,4);
    	sop(d);
    }
    
    public static void sop(String s) {
		System.out.println(s);
	}
}

3、获取一个字符串在另一个字符串中出现的次数

代码:

public class code
{
	public static int method_get(String str,String key) {
		int count = 0;
		int index = 0;
		while((index=str.indexOf(key))!=-1) {
//		while((index=str.indexOf(key,index))!=-1) {
			str=str.substring(index+key.length());
//			index=index+key.length());
			count++;
		}
		return count;
	}

	public static void main(String[] args) {
    	String str="abckbwockbkpkbk";
    	String tr="kb";
    	int d1=str.split("kb").length);//不建议使用分割的方法,不全面
    	int d2=method_get(str,tr);
    	System.out.println(d2);
    }
    
//    public static void sop(String s) {
//		System.out.println(s);
//	}
}

4、获取两个字符串最大相同子串。

public class code
{
	public static String method_get(String str,String key) {
		int i,j,k;
		String max="",min="";
		max=(str.length()>key.length())?str:key;
		min=(max==str)?key:str;
		
		for(i=0;i<min.length();i++) {
			for(j=0,k=min.length()-i;k!=min.length()+1;k++,j++) {
				String temp=min.substring(j,k);
				if(str.contains(temp))
					return temp;
			}
		}
		return "";
	}

	public static void main(String[] args) {
    	String str="abckbwockbkpkk";
    	String tr="alikbkdop";
    	sop(method_get(str,tr));
    }
    
    public static void sop(Object obj) {
		System.out.println(obj);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值