字符串压缩
import com.sun.org.apache.xml.internal.utils.StringComparable;
import java.lang.reflect.Array;
import java.util.Scanner;
class TestDemo3 {
public static String stringCompress(String str) {
StringBuilder buf = new StringBuilder();
char[] as = str.toCharArray();
char as1 = str.charAt(0);
int count =1;
for ( int i=0;i<as.length ;i++){
char as2=str.charAt(i) ;
if (as2==as1){
count++;
continue;
}
buf=buf.append(count).append(as1) ;
//append 是StringBuffer类的一个方法,把两个字符加起来。
count=1;
as1=as2;
buf=buf.append(count).append(as1) ;
return buf.toString() ;
}
return str;
}
public static void main (String[] args){
System.out.println("请输入字符串");
stringCompress(str) ;
Scanner.scanner=new Scanner(System .in ) ;
String.str=nextline();
System.out.println(StringComparable(str));
}
}
数组逆置
public class ReserveInstence{
public static void reserve(char[] arr, int begin, int end) {
while(begin < end) {
char temp = arr[begin];
arr[begin] = arr[end];
arr[end] = temp;
begin++;
end–;
}
}
public static String reserveWords(String str) {
char[] arr = str.toCharArray();
reserve(arr, 0, arr.length - 1);
int begin = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == ’ ') {
reserve(arr, begin, i - 1);
begin = i + 1;
}
}
return new String(arr);
}
public static void main(String[] args) {
String str="I love china";
System.out.println(reserveWords(str));
}
}