1. 程式人生 > >java的String和StringBuilder方法

java的String和StringBuilder方法

n) string 字符串 插入 input charat stringbu index insert

String s1="hello lxx";
String s2=new String("fff df");
System.out.println(s1.length());
System.out.println(s1.substring(0, 2));
System.out.println(s1.equals(s2));
System.out.println(s1.charAt(3));
System.out.println(s1.replace("o","r"));
System.out.println(s1.indexOf("l"));
StringBuilder s3=new StringBuilder("hello nihao");
System.out.println(s3.append("a"));
// 打印s3的容量capacity()
System.out.println(s3.capacity());
//在2的位置插入b字符串
System.out.println(s3.insert(2, "b"));
System.out.println(s3.delete(2, 3));
//reverse反轉
System.out.println(s3.reverse());

運行結果

9
he
false
l
hellr lxx
2
hello nihaoa
27
hebllo nihaoa
hello nihaoa
aoahin olleh

Scanner input=new Scanner(System.in);
StringBuilder s1=new StringBuilder( input.nextLine());
System.out.println(s1.reverse());
Scanner s2=new Scanner(System.in);
System.out.println("請輸入字符串:");
String str=s2.nextLine();
String reverse = "";
for(int i=str.length()-1;i>=0;i--){
reverse+=str.charAt(i);
}
System.out.println(reverse);

運行結果

gggdfgh
hgfdggg
請輸入字符串:
gbhnf
fnhbg

java的String和StringBuilder方法