Java-认识String

目录

一、String概念及创建

        1.1 String概念

         1.2 String的创建

二、String常用方法

        2.1 String对象的比较

        2.2  字符串查找

        2.3 转化

        2.4  字符串替换

        2.5 字符串拆分

                 2.6字符串的截取

        2.7 其他操作方法

                 2.8 字符串修改

        2.9 StringBuilder和StringBuffer

三、面试题


一、String概念及创建

        1.1 String概念

                Java中字符串是由字符组成的一个字符数组,是复合数据类型,也是一种引用类型。所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象;String类中的字符实际保存在内部维护的value字符数组中
 

         1.2 String的创建

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

        //常量字符串构造

        String str="hello word";

        System.out.println(str);

        //new String对象

        String str1=new String("hello!");

        System.out.println(str1);

        //用字符数组构造

        char[] chars={'h','e','l','l','o',' ','w','o','r','l','d'};

        String str2=new String(chars);

        System.out.println(str2);

        

        注意:String是引用类型,内部并不存储字符串本身,而是存储一个地址,在Java中“”引起来的也是String类型对象。

        String s1="hello";

        String s2="world";

        String s3=s1;

        

二、String常用方法

           由于字符串是不可变对象, 不是修改当前字符串, 而是产生一个新的字符串

        2.1 String对象的比较

                字符串的比较是常见操作之一,Java中提供了4中方式:

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

        int a=5;
        int b=10;
        //基本数据类型变量,==比较两个变量的值
        System.out.println(a==b);
        //引用类型变量,==比较两个引用变量引用是否为同一对象
        String s1="hello";
        String s2="world";
        String s3="hello";
        String s4=s1;
        System.out.println(s1==s2);
        System.out.println(s1==s3);
        System.out.println(s1==s4);

                

         2.boolean equals(Object anObject) 方法,比较字符串的内容是否相等,返回的是boolean类型。

        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("Hello");
        //s1、s2、s2引用对象不同,但s1和s2内容相同
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));

                

                3.int compareTo(String s) 方法

                compareTo返回的是int类型,比较方式: 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值;如果前k个字符相等(k为两个字符长度最小值),返回两个字符串长度差值。

String s1=new String("abc");
String s2=new String("ac");
String s3=new String("abc");
String s4=new String("abcdef");
System.out.println(s1.compareTo(s2));//输出字符差值-1
System.out.println(s1.compareTo(s3));//输出0
System.out.println(s1.compareTo(s4));//输出长度差值-3

         4. int compareToIgnoreCase(String str) 方法:与compareTo方式相同,但是忽略大小写比较。

   String s1=new String("abc");
   String s2=new String("ac");
   String s3=new String("ABC");
   String s4=new String("abcdef");
   System.out.println(s1.compareToIgnoreCase(s2));//输出字符差值
   System.out.println(s1.compareToIgnoreCase(s3));//输出0
   System.out.println(s1.compareToIgnoreCase(s4));//输出长度差值

                

        2.2  字符串查找

                字符串查找也是字符串中非常常见的操作,String类提供的常用查找的方法:
 

方法 功能
char charAt(int index) 查找并返回index位置上字符,如果index为负数或者越界,抛出异常
int indexOf(int ch) 查找并返回ch第一次出现的位置,没有返回-1
int indexOf(char ch, int fromIndex)

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

查找并返回str第一次出现的位置,没有返回-1

int indexOf(String str, int fromIndex)

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

int lastIndexOf(char 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
 
String s1="aabbccaabbcc";
System.out.println(s1.charAt(2)); //b
System.out.println(s1.indexOf('c'));  //4
System.out.println(s1.indexOf('b',4));  //8
System.out.println(s1.indexOf("bbcc"));     //2
System.out.println(s1.indexOf("bcc",4));  //9
System.out.println(s1.lastIndexOf('c'));    //11
System.out.println(s1.lastIndexOf('c',6));  //5
System.out.println(s1.lastIndexOf("bcc"));      //9
System.out.println(s1.lastIndexOf("bcc",8));  //3

         2.3 转化

                1.数字和字符串转化 String.valueOf、Integer.parseInt、Double.parseDouble

                //数字转字符串

        String s1=String.valueOf(15);
        String s2=String.valueOf(1.5);
        String s3=String.valueOf(true);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);

                

         //字符串转数字,Integer、Double是Java中的包装类型

        int s1=Integer.parseInt("15");

        double s2=Double.parseDouble("1.5");

        System.out.println(s1);

        System.out.println(s2);

                2.大小写转换 toUpperCase、toLowercase

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

                

               3.字符串数组转化  toCharArray、new String()

    public static void main(String[] args) {
            String s1="hello";
            //字符串转化为字符数组
            char[] ch=s1.toCharArray();
            for (char ch1:ch) {
                System.out.println(ch1);
            }
            //字符数组转化为字符串
            String s2=new String(ch);
            System.out.println(s2);
}

                

                 4.格式化  format

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

                

        2.4  字符串替换

                使用一个指定的新的字符串替换掉已有的字符串数据。
        

方法 功能
String replaceAll(String regex, String replacement) 替换所有的指定内容
String replaceFirst(String regex, String replacement) 替换首个指定内容
public static void main(String[] args) {
    String s1="helloworld";
    String s2=s1.replaceAll("|","_");
    System.out.println(s2);
    String s3=s1.replaceFirst("|","_");
    System.out.println(s3);
}

                

        2.5 字符串拆分

                可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。
                

方法 功能
String[] split(String regex) 将字符串全部拆分
String[] split(String regex, int limit) 将字符串以指定格式拆分为limit组
        public static void main(String[] args) {
            String s1="hello word good afternoon";
            String[] s2=s1.split(" ");//全部拆分
            for (String str:s2) {
                System.out.println(str);
            }
        }

                          

        public static void main(String[] args) {
            String s1="hello word good afternoon";
            String[] s2=s1.split(" ",2);//拆分为两部分
            for (String str:s2) {
                System.out.println(str);
            }
       }

                 

         有些特殊字符作为分割符可能无法正确切分, 需要加上转义。

        例如:拆分IP地址

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

        }

        

        注意:字符"|","*","+"都得加上转义字符,前面加上 "\\";而如果是 "\" ,那么就得写成 "\\\\";如果一个字符串中有多个分隔符,可以用"|"作为连字符。

        多次拆分

public static void main(String[] args) {
    String str = "name=zhangsan&age=18";
    String[] s1=str.split("&");
    for (int i = 0; i < s1.length; i++) {
        String[]  s2=s1[i].split("=");
        for (String ch:s2) {
            System.out.println(ch);
        }
    }
}

                

                 2.6字符串的截取

                从一个完整的字符串之中截取出部分内容。

方法 功能
String substring(int beginIndex) 从指定索引截取到结尾
String substring(int beginIndex, int endIndex) 截取部分内容
        public static void main(String[] args) {
            String s="helloworld";
            System.out.println(s.substring(3));
            System.out.println(s.substring(2,5));//左闭右开
        }

                        

         2.7 其他操作方法

                

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

         String st=" hello world ";

         System.out.println("["+st+"]");

         System.out.println("["+st.trim()+"]");

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

                   

                2.8 字符串修改

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

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

                这种方式不推荐使用,如果要修改建议尽量使用StringBuffer或者StringBuilder。

        2.9 StringBuilder和StringBuffer

            由于String的不可更改特性,为了方便字符串的修改,Java中又提供StringBuilder和StringBuffer类。这两个类大部分功能是相同的,这里介绍 StringBuilder常用的一些方法。

                

方法 说明
StringBuff append(String
str)
在尾部追加,相当于String的+=,可以追加:boolean、char、char[]、
double、float、int、long、Object、String、StringBuff的变量
char charAt(int index) 获取index位置的字符
int length() 获取字符串的长度
int capacity() 获取底层保存字符串空间总的大小
void ensureCapacity(int
mininmumCapacity)
扩容
void setCharAt(int index,
char ch)
将index位置的字符设置为ch
int indexOf(String str) 返回str第一次出现的位置
int indexOf(String str, int
fromIndex)
从fromIndex位置开始查找str第一次出现的位置
int lastIndexOf(String str) 返回最后一次出现str的位置
int lastIndexOf(String str,
int fromIndex)
从fromIndex位置开始找str最后一次出现的位置
StringBuff insert(int
offset, String str)
在offset位置插入:八种基类类型 或 String类型 或Object类型数据
StringBuffer
deleteCharAt(int index)
删除index位置字符
StringBuffer delete(int
start, int end)
删除[start, end)区间内的字符
StringBuffer replace(int
start, int end, String str)
将[start, end)位置的字符替换为str
String substring(int start) 从start开始一直到末尾的字符以String的方式返回
String substring(int
start,int end)
将[start, end)范围内的字符以String的方式返回
StringBuffer reverse() 反转字符串
String toString() 将所有字符按照String的方式返回

        public static void main(String[] args) {
                StringBuilder sb1 = new StringBuilder("hello");
                StringBuilder sb2 = sb1;


                // 追加:即尾插-->字符、字符串、整形数字

                sb1.append(' '); // hello
                sb1.append("world"); // hello world
                sb1.append(123); // hello world123
                System.out.println(sb1); // hello world123
                System.out.println(sb1 == sb2); // true


                System.out.println(sb1.charAt(0)); // 获取0号位上的字符 h
                System.out.println(sb1.length()); // 获取字符串的有效长度14
                System.out.println(sb1.capacity()); // 获取底层数组的总大小


                sb1.setCharAt(0, 'H'); // 设置任意位置的字符 Hello world123

                 // 在对应位置插入字符串
                sb1.insert(0, "Hello world!!!");//Hello world!!!Hello world123
                System.out.println(sb1);


                System.out.println(sb1.indexOf("Hello")); // 获取Hello第一次出现的位置
                System.out.println(sb1.lastIndexOf("hello")); // 获取hello最后一次出现的位置


                sb1.deleteCharAt(0); // 删除首字符
                sb1.delete(0,5); // 删除[0, 5)范围内的字符


                String str = sb1.substring(0, 5); // 截取[0, 5)区间中的字符以String的方式返回
                System.out.println(str);
                sb1.reverse(); // 字符串逆转
                str = sb1.toString(); // 将StringBuffer以String的方式返回
                System.out.println(str)

        }

        String和StringBuilder最大的区别在于String的内容无法修改,而StringBuilder的内容可以修改。频繁修改字符串的情况考虑使用StringBuilder。
        注意:String和StringBuilder类不能直接转换。如果要想互相转换,可以采用如下原则:

  • String变为StringBuilder: 利用StringBuilder的构造方法或append()方法
  •  StringBuilder变为String: 调用toString()方法

三、面试题

        1. String、StringBuffer、StringBuilder的区别

                String的内容不可修改,StringBuffer与StringBuilder的内容可以修改;StringBuffer与StringBuilder大部分功能是相似的;StringBuffer采用同步处理,属于线程安全操作;StringBuilder未采用同步处理,属于线程不安全操作。
 

猜你喜欢

转载自blog.csdn.net/qq_64668629/article/details/132145944