字符及字符串的一般应用

1.字符的尾部填充

public class Test17{
	public static void main(String[] args){
		System.out.println(fillBefore("avsg",'t',8));
	}
	public static String fillBefore(String str, char filledChar, int len) {
	
		if(str.length() >= len){
			return str;
		}
		else{
			StringBuffer sb = new StringBuffer(str);
			for(int i = sb.length();i < len;i++){
				sb.insert(sb.length(),filledChar);
			}
			return sb.toString();
			
		}
	}
}

2.字符的首部填充,只需改填充的位置即可

public class Test17{
	public static void main(String[] args){
		System.out.println(fillBefore("avsg",'t',8));
	}
	public static String fillBefore(String str, char filledChar, int len) {
	
		if(str.length() >= len){
			return str;
		}
		else{
			StringBuffer sb = new StringBuffer(str);
			for(int i = sb.length();i < len;i++){
				sb.insert(sb.0,filledChar);
			}
			return sb.toString();
			
		}
	}
}

3移除字符串中所有给定字符串


public class removeAll{
	public static void main(String[] args){
		remove();
	}
	static void remove(){
		String str ="  hello,world"  ;
		System.out.println("移除前的字符串为"+str);
		System.out.println("移除指定的字母0");
		System.out.println("移除l后的字符串为:");
		String str1=str.replaceAll("0", "");//将l移除,其实替换,不过替换的内容为空,如果将引号中给一个内容,就会替换
	    System.out.println("["+str1.trim()+"]");//将str两边的空格删掉
		//我们再次移除一个字母d
		System.out.println("移除一个字母d后的字符串为:");
		String str2=str1.replaceAll("d","");
		System.out.println(str2);
		//再将o字母替换为i like you
		System.out.println("替换后的字符串为:");
		String str3 =str2.replaceAll("o","i like you");
		System.out.println(str3);
	}
}

4.String类扩展功能实现


public class Test15{
	public static void main(String[] args){
    //   char[] data ={'a'};
	//for(int i =0;data.length<6;++i){			
	//	data[i]=data[1];
	//}	
	//System.out.println(data);
	
	System.out.println(repeat('q',7));
	}
	public static String repeat(char c,int count){
		if(count <= 0){
			return "";
		}
		char [] data; 
		data = new char [count];
		for(int i = 0;i < count;i++){
			data[i] = c;
		}
		return (new String(data));
	}
}

5反转字符串


 public class Reverse{
	 public static void main(String[] args){
		 reverse();
	 }
	 static void reverse(){
		 String str = "i am winner";
		 System.out.println("反转前的字符串为"+str);
		 //StringBuffer str1 = new StringBuffer(str);
		 System.out.println("反转之后的字符串为");
       StringBuffer str1 = new StringBuffer(str);
	   System.out.println(str1.reverse());
	String str2 =str.replaceAll(" ","");//把里面的空格去掉;
	System.out.println("去掉空格的str 为:");
	System.out.println(str2);
	System.out.println("反转之后str2为:");
	StringBuffer str3 =new StringBuffer(str2);
	System.out.println(str3.reverse());
	 }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值