public final class String
final修饰,一旦创建了 String 对象,那它的值就无法改变了
String str1 = new String("aaa");
如果单纯这样的语句毫无疑问创建了两个对象。
- String str = "aaa";
- String str1 = new String("aaa");
如果第二种方式需要注意:
第二句创建方式则创建了一个对象,因为aaa是从字符串常量池中取出来的。
和数组一样的方式:
- String str = "aaa";
- int len = str.length;
(1)charAt() 方法:charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1
- public class Test {
- public static void main(String args[]) {
- String s = "abcd";
- char result = s.charAt(1);
- System.out.println(result);//结果是:b
- }
- }
(2)compareTo() 方法两种方式的比较:字符串与对象进行比较,按字典顺序比较两个字符串。
- public class Test {
- public static void main(String args[]) {
- String str1 = "abc";
- String str2 = "abc";
- String str3 = "abc123";
-
- int result = str1.compareTo( str2 );
- System.out.println(result);// 结果是0,两个字符串内容相同
-
- result = str2.compareTo( str3 );
- System.out.println(result);//结果是-3.str2比str3短,输出是负数
-
- result = str3.compareTo( str1 );
- System.out.println(result);// 结果是3,str3比str1长,输出是正数
- }
- }
(3) split() 方法:才分字符串
- public class Test {
- public static void main(String args[]) {
-
- String str3 = new String("acount=? and uu =? or n=?");
- System.out.println("多个分隔符返回值 :" );
- for (String retval: str3.split("and|or")){
- System.out.println(retval);
- //多个分隔符返回值 :
- //acount=?
- //uu =?
- //n=?
- }
- }
- }
(4)substring() 方法:返回字符串的子字符串
- public class RunoobTest {
- public static void main(String args[]) {
- String Str = new String("abc def");
-
- System.out.print("返回值 :" );
- System.out.println(Str.substring(1, 5));
- //结果:c d
- //从第1个后面截到第5个前面,也就是索引2,3,4
- }
- }
(5)substring() 方法:返回字符串的子字符串
- public static void main(String[] args) {
- //将字符串解析为int类型
- String str = "100";
- //方式1
- Integer i = Integer.valueOf(str);
- int num = i.intValue();
- //方式2
- int number = Integer.parseInt(str);
- }
(6)字符串替换:replace("A","B")
字母B替换字母A
- String s = "ABC";
- String result = s.replace("A","B");