java字符串按字符逆转和按单词逆转

字符串的处理,经常在各类考试中用到,在网上搜索了下这方面的资料却很少,于是翻了下文档自己做了两个小demo.

1.将字符串按单个字符逆转代码:

package javastring;
public class CharReverse {
public String wordReverse(String str){
	int n=str.length();
	char []chars=new char[n];
	str.getChars(0, n, chars, 0);//获得了char[]可操作的数组.
	
	int length=chars.length;
	StringBuffer sbStr=new StringBuffer();
	for(int i=0;i<length;i++){
		sbStr.append(chars[length-i-1]+"");//用StringBuffer将其逆转.
	}
	return sbStr.toString();//转换为String
}
public static void main(String args[]){
	CharReverse cr=new CharReverse();
	String str="I really love you!";
	System.out.println("Before reverse:"+str);
	
	String str2=cr.wordReverse(str);//仅静态调动非静态要用对象.声明
	System.out.println("After reverse:"+str2);
	
}
}

 2.将字符串按单词逆转代码:

package javastring;
public class WordReverse {
	public String wordReverse(String str){
		String stringArray[]=str.split(" ");//获得按word划分String可操作数组.
		StringBuffer sbStr=new StringBuffer();
		int length=stringArray.length;
		for(int i=0;i<length;i++){
			sbStr.append(stringArray[length-i-1]+" ");//用StringBuffer将其逆转.
			}
		return sbStr.toString();//转换为String.
	}
public static void main(String args[]){
	WordReverse wr=new WordReverse();
	String str="So that is true.";
	System.out.println("Before word reverse:"+str);
	String str2=wr.wordReverse(str);
	System.out.println("Before word reverse:"+str2);
}
}
 

 

你可能感兴趣的:(java)