String类

1. String类的重要性

在C语言中已经涉及到字符串了,但是在C语言中要表示字符串只能使用字符数组或者字符指针,可以使用标准库提 供的字符串系列函数完成大部分操作,但是这种将数据和操作数据方法分离开的方式不符合面相对象的思想,而字 符串应用又非常广泛,因此Java语言专门提供了String类。

2. 常用方法

2.1 字符串构造

String类提供的构造方式非常多,常用的就以下三种:

public static void main(String[] args) {
 // 使用常量串构造
String s1 = "hello bit";
 System.out.println(s1);
 // 直接newString对象
String s2 = new String("hello bit");
 System.out.println(s1);
 // 使用字符数组进行构造
char[] array = {'h','e','l','l','o','b','i','t'};
 String s3 = new String(array);
 System.out.println(s1);
 }

String是引用类型,内部并不存储字符串本身 

2.2 String对象的比较

1. ==比较是否引用同一个对象

注意:对于内置类型,==比较的是变量中的值;对于引用类型==比较的是引用中的地址

2. boolean equals(Object anObject)方法:按照字典序比较字典序:字符大小的顺序

String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照 如下规则进行比较,比如:s1.equals(s2)

public boolean equals(Object anObject) {
    // 1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
      if (this == anObject) {
         return true;
    }
    
    // 2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
       if (anObject instanceof String) {
        // 将anObject向下转型为String类型对象
          String anotherString = (String)anObject;
          int n = value.length;
        
        // 3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            
            // 4. 按照字典序,从前往后逐个字符进行比较
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

2.3 字符串查找

char charAt(int index)        返回index位置上字符,如果index为负数或者越界,抛出                                                                 IndexOutOfBoundsException常

int indexOf(int ch)             返回ch第一次出现的位置,没有返回-1

int indexOf(int ch, int fromIndex)   从fromIndex位置开始找ch第一次出现的位置,没有返回-1

int indexOf(String str)                    返回str第一次出现的位置,没有返回-1

int indexOf(String str, int fromIndex)     从fromIndex位置开始找str第一次出现的位置,没有返                                                                     回-1

int lastIndexOf(int ch)           从后往前找,返回ch第一次出现的位置,没有返回-1

int lastIndexOf(int ch, int fromIndex)    从fromIndex位置开始找,从后往前找ch第一次出现的                                                                      位置,没有返回-1

int lastIndexOf(String str)      从后往前找,返回str第一次出现的位置,没有返回-1

int lastIndexOf(String str, int fromIndex)   从fromIndex位置开始找,从后往前找str第一次出                                                                         现 的  位置,没有返回-1                                                              

public static void main(String[] args) {
    String s = "aaabbbcccaaabbbccc";
    System.out.println(s.charAt(3));                             // 'b'
    System.out.println(s.indexOf('c'));                          // 6
    System.out.println(s.indexOf('c', 10));                      // 15
    System.out.println(s.indexOf("bbb"));                        // 3
    System.out.println(s.indexOf("bbb", 10));                    // 12
    System.out.println(s.lastIndexOf('c'));                      // 17
    System.out.println(s.lastIndexOf('c', 10));                  // 8
    System.out.println(s.lastIndexOf("bbb"));                    // 12
    System.out.println(s.lastIndexOf("bbb", 10));                // 3
}

2.4 转化

1. 数值和字符串转化

 public static void main(String[] args) {
    // 数字转字符串
    String s1 = String.valueOf(1234);
    String s2 = String.valueOf(12.34);
    String s3 = String.valueOf(true);
    String s4 = String.valueOf(new Student("Hanmeimei", 18));
    System.out.println(s1);
    System.out.println(s2);
    System.out.println(s3);
    System.out.println(s4);
    System.out.println("=================================");
    // 字符串转数字
    // 注意:Integer、Double等是Java中的包装类型,这个后面会讲到
    int data1 = Integer.parseInt("1234");
    double data2 = Double.parseDouble("12.34");
    System.out.println(data1);
    System.out.println(data2);
 }

2. 大小写转换

public static void main(String[] args) {
    String s1 = "hello";
    String s2 = "HELLO";
    // 小写转大写
    System.out.println(s1.toUpperCase());
    // 大写转小写
    System.out.println(s2.toLowerCase());
 }

3. 字符串转数组

 public static void main(String[] args) {
    String s = "hello";
    // 字符串转数组
    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        System.out.print(ch[i]);
    }
    System.out.println();
    // 数组转字符串
    String s2 = new String(ch);
    System.out.println(s2);
 }

 4. 格式化

public static void main(String[] args) {
    String s = String.format("%d-%d-%d", 2019, 9,14);
    System.out.println(s);
 }

2.5 字符串替换 

String replaceAll(String regex, String replacement)    替换所有的指定内容

String replaceFirst(String regex, String replacement)   替换首个内容

String str = "helloworld" ; 
System.out.println(str.replaceAll("l", "_"));
System.out.println(str.replaceFirst("l", "_"));

注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串. 

2.6 字符串拆分

String[] split(String regex)                   将字符串全部拆分

String[] split(String regex, int limit)     将字符串以指定的格式,拆分为limit组

示例:实现字符串的拆分处理

 String str = "hello world hello bit" ; 
 String[] result = str.split(" ") ; // 按照空格拆分
 for(String s: result) {
    System.out.println(s);
 }

 示例:字符串的部分拆分

 String str = "hello world hello bit" ; 
 String[] result = str.split(" ",2) ; 
 for(String s: result) {
    System.out.println(s);
 }

拆分是特别常用的操作. 一定要重点掌握. 另外有些特殊字符作为分割符可能无法正确切分, 需要加上转义 

示例:拆分IP地址

String str = "192.168.1.1" ; 
String[] result = str.split("\\.") ; 
for(String s: result) {
    System.out.println(s);
 }

注意事项: 

1. 字符"|","*","+"都得加上转义字符,前面加上"\\".

2. 而如果是"\",那么就得写成"\\\\".

3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符.

多次拆分

String str = "name=zhangsan&age=18" ; 
String[] result = str.split("&") ;
 for (int i = 0; i < result.length; i++) {
    String[] temp = result[i].split("=") ; 
    System.out.println(temp[0]+" = "+temp[1]);
 }

2.7 字符串截取 

String substring(int beginIndex)      从指定索引截取到结尾

String substring(int beginIndex, int endIndex)   截取部分内容

示例: 观察字符串截取

 String str = "helloworld" ; 
 System.out.println(str.substring(5));
 System.out.println(str.substring(0, 5));

2.8 其他操作方法

String trim()                去掉字符串中的左右空格,保留中间空格

String toUpperCase()  字符串转大写

String toLowerCase()   字符串转小写

示例: 观察trim()方法的使用

String str = "   hello  world   " ; 
System.out.println("["+str+"]");
System.out.println("["+str.trim()+"]");

trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等). 

示例: 大小写转换

String str = "   hello%$$%@#$%world 哈哈哈  " ; 
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());

这两个函数只转换字母。 

2.9 字符串的不可变性

String是一种不可变对象. 字符串中的内容是不可改变。字符串不可被修改,是因为:

1. String类在设计时就是不可改变的,String类实现描述中已经说明了

2. 所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象

final修饰类表明该类不想被继承,final修饰引用类型表明该引用变量不能引用其他对象,但是其引用对象中的内 容是可以修改的。

public static void main(String[] args) {
 final int array[] = {1,2,3,4,5};
 array[0] = 100;
 System.out.println(Arrays.toString(array));
 // array = new int[]{4,5,6};    // 编译报错:Error:(19, 9) java: 无法为最终变量array分配值
}

2.10 字符串修改 

注意:尽量避免直接对String类型对象进行修改,因为String类是不能修改的,所有的修改都会创建新对象,效率 非常低下。

public static void main(String[] args) {
    String s = "hello";
    s += " world";
    System.out.println(s);  // 输出:hello world
 }

但是这种方式不推荐使用,因为其效率非常低,中间创建了好多临时对象。

可以看待在对String类进行修改时,效率是非常慢的,因此:尽量避免对String的直接需要,如果要修改建议尽量 使用StringBuffer或者StringBuilder。 

  • 14
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值