string的使用
String和StringBuffer区别以及常见方法
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "This is a book!";
int i = s.length();
// 返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
String sub_s = s.substring(8);
String s1 = s.toUpperCase();
String s2;
s2 = s.replace('!', '.');
System.out.println("sub_s=" + sub_s);
System.out.println("s1=" + s1);
System.out.println("s2=" + s2);
System.out.println("s=" + s);//String无论怎么修改,怎么变,原来的字符串都没有变
// .............................................................
StringBuffer ss = new StringBuffer("drink java!");
ss.insert(6, "Hot");
System.out.println("ss=" + ss);
ss.setCharAt(0, 'D');
System.out.println("ss=" + ss);//ss变化了
String s_int = "1234";
i = Integer.parseInt(s_int);// 字符串中的字符都必须是十进制数字。返回得到的整数值,就好像将该参数和基数 10
System.out.println(i);
}
}
总结:
1.String不可以改,Stringbuffer可以改
怎么理解呢?你运行一下就会发现:String无论怎么修改,怎么变,原来的字符串s都没有变。而Stringbuffer反之。
==和equal
package string;
public class TestEqual {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = new String("abc");
String s2 = new String("ABC");
String s3 = new String("abc");
boolean b = s1.equals(s2);
boolean b2 = s1.equalsIgnoreCase(s2);
System.out.println(s1 + "equals" + s2 + ":" + b);
System.out.println(s1 + "equalsIgnoreCase" + s2 + ":" + b2);
System.out.println(".................string对象比较。。。。。。。。。。。");
b = (s1 == s3);
System.out.println("s1==s3" + b);
String s4 = "abc";
String s5 = "abc";
String s6 = "abcd";
System.out.println(".................string字符串比较。。。。。。。。。。。");
b = (s4 == s5);
System.out.println("s4==s5" + b);
b = (s4 == s6);
System.out.println("s4==s6" + b);
s6 = "abc";
b = (s4 == s6);
System.out.println("s4==s6" + b);
}
}
总结:
1、比较和equal不同
2、new后是字符串对象,若是同名对象,必须使用equals才等,不能使用
3.String字符串s1,s2,s3…如果字符串相等存储在同一地址下
练习
package string;
public class StringAppend {
public static String appendName(String s[], char c) {
StringBuffer sname = new StringBuffer("");
for (int i = 0; i < s.length - 1; i++) {
sname.append(s[i] + String.valueOf(c));
}
sname.append(s[s.length - 1]);
return sname.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = new String[3];
for (int i = 0; i < s.length; i++)
s[i] = "name" + (i + 1);
System.out.println(appendName(s, ','));
}
}
总结 :按照格式要求输出,故意保留最后一个姓名,最后添加到结尾,以免出现name1,name2,name3,
1.字符转字符串 String.valueof() .为什么可以String.因为String是静态类,直接String.就可以,类似的还有Math. 等
2.字符串数组转字符串 数组名.toString()