【String类的常用方法】

简介: 【String类的常用方法】

字符串构造

public class Test {
    public static void main(String[] args) {
        String str = "hello";
        System.out.println(str);
        String str2 = new String("hehehe");
        System.out.println(str2);
        char[] array = {'a','b','c'};
        String str3 = new String(array);
        System.out.println(str3);
    }
}
public class Test {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;
        System.out.println(s3);
        String s4 = "";//存储0
        System.out.println(s4.length());
        System.out.println(s4.isEmpty());
        String s5 = null;//不存任何数
        System.out.println(s5.length());
        System.out.println(s5.isEmpty());
    }
  1. String是引用类型,内部并不存储字符串本身,

String对象的比较

1.== //比较地址

2. equals //比较值相不相等

3.compareTo //比较值的大小

4.compareToIgnoreCase//忽略大小写比较

public class Test {
    public static void main(String[] args) {
        String s1 ="Student";
        String s2 ="Student";
        System.out.println(s1==s2);//比较值
        String s3 = new String("JAVA");
        String s4 = new String("JAVA");
        System.out.println(s3 == s4);//比较地址一样不一样
        System.out.println(s3.equals(s4));//比较值
        String s5 ="abc";
        String s6 ="adc";
        //s5>s6 返回正数
        //s5==s6 返回0
        //s5<s6 返回负数
        System.out.println(s5.compareTo(s6));
        //忽略大小写比较
        String s7 ="abc";
        String s8 ="ABC";
        System.out.println(s7.compareToIgnoreCase(s8)); //0
    }
    public static void main3(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;
        System.out.println(s3);//hello
        String s4 = "";//存储0
        System.out.println(s4.length());
        System.out.println(s4.isEmpty());
        String s5 = null;//不存任何数
       // System.out.println(s5.length());
        System.out.println(s5.isEmpty());
    }
    public static void main2(String[] args) {
        String str = "hello";
        System.out.println(str);
        String str2 = new String("hehehe");
        System.out.println(str2);
        char[] array = {'a','b','c'};
        String str3 = new String(array);
        System.out.println(str3);//abc
    }
  }
}

字符串查找

charAt

找到字符串某个字符的下标的元素

public class Test {
    public static void main(String[] args) {
        //charAt
        String s1 ="English";
        char ch = s1.charAt(3);//3下标的值
        System.out.println(ch);
        //遍历字符串
        for (int i = 0; i <s1.length() ; i++) {
            char sh = s1.charAt(i);
            System.out.print(sh);
        }
    }
}

indexof

int indexOf(int ch)

在字符串中 第一次出现某个字符的下标,没有返回-1

public class Test {
    public static void main(String[] args) {
        String str = "abacabc";
       int index = str.indexOf('a');//字符串中第一次出现字符a的下标
        System.out.println(index);
    }
}

int indexOf(int ch, int fromIndex)

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

public class Test {
    public static void main(String[] args) {
        String str = "abacabc";
        int index = str.indexOf('a',3);
        System.out.println(index);
    }
}

int indexOf(String str)

返回字符串第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String str = "abacabc";
        int index = str.indexOf("abc");
        System.out.println(index);//4
    }
}

int indexOf(String str, int fromIndex)

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

public class Test {
    public static void main(String[] args) {
        String str = "acabacb";
        int index = str.indexOf("ab",2);
        System.out.println(index);
    }
}

int lastIndexOf(int ch)

从后往前找,返回字符第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String str = "acabacb";
        int index = str.lastIndexOf('b');
        System.out.println(index);//6
    }
}

int lastIndexOf(int ch, int fromIndex)

从fromIndex位置开始找,从后往前找字符第一次出现的位置,没有返

回-1

public class Test {
    public static void main(String[] args) {
        String str = "acabacb";
        int index = str.lastIndexOf('b',5);
        System.out.println(index);//3
    }
}

int lastIndexOf(String str)

从后往前找,返回字符串第一次出现的位置,没有返回-1

public class Test {
    public static void main(String[] args) {
        String str = "acabacb";
        int index = str.lastIndexOf("ac");
        System.out.println(index);//4
    }
}

int lastIndexOf(String str, int fromIndex)

从fromIndex位置开始找,从后往前找字符串第一次出现的位置,没有返

回-1

public class Test {
    public static void main(String[] args) {
        String str = "acabacb";
        int index = str.lastIndexOf("ac",3);
        System.out.println(index);//0
    }
}

转化

1. 数值和字符串转化

数字转字符串

public class Test {
    public static void main(String[] args) {
        //数字转字符串
        String s1 =  String.valueOf(1919);//整型
        String s2 =  String.valueOf(19.9);//浮点型
        System.out.println(s1);//变成字符串了
        System.out.println(s2);
    }

字符串转数字

public class Test {
    public static void main(String[] args) {
       int date = Integer.parseInt("198");//整型转字符串
      double date2 = Double.parseDouble("15.55");//浮点型转字符串
        System.out.println(date);
        System.out.println(date2);
    }
}

2.大小写转换 toUpperCase toLowerCase

public class Test {
    public static void main(String[] args) {
        String s1 = "hello";
        System.out.println(s1.toUpperCase());//HELLO
        String s2 = "WORLD";
        System.out.println(s2.toLowerCase());//world
    }

3.字符串转数组 toCharArray

public class Test {
    public static void main(String[] args) {
        String s1 = "hello";
        char[] array = s1.toCharArray();
        System.out.println(Arrays.toString(array));//Arrays.toString( )是打印数组的
    }
}

4.数组转字符串

public class Test {
    public static void main(String[] args) {
        char[] array ={'h','e','l','l','o'};
        String s1 = new String(array);
        System.out.println(s1);
    }
}

5.格式化 format

public class Test {
    public static void main(String[] args) {
        String s =String.format("%d-%d-%d",2023,11,06);
        System.out.println(s);//2023-11-06
    }

字符串替换

String replaceAll(String regex, String replacement)

替换所有的指定内容

public class Test {
    public static void main(String[] args) {
        String str = "abbaacca";
        System.out.println(str.replaceAll("b","q"));//aqqaacca
        System.out.println(str);//abbaacca
    }
}

String replaceFirst(String regex, String replacement)

替换首个内容

public class Test {
    public static void main(String[] args) {
        String str = "abbaacca";
        String s1 = str.replaceFirst("b","88");
        System.out.println(s1);
    }

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

字符串拆分

以空格拆分

public class Test {
    public static void main(String[] args) {
        String str = "hello beautiful world";
        String [] s1 = str.split(" ");
        for (int i = 0; i < s1.length; i++) {
            System.out.println(s1[i]);
        }
    }

以空格分开,分成两组

public class Test {
    public static void main(String[] args) {
        String str = "hello beautiful world";
        String [] s1 = str.split(" ",2);
        for (int i = 0; i < s1.length; i++) {
            System.out.println(s1[i]);
        }
    }

特殊字符拆分

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

public class Test {
// 拆分IP地址
    public static void main(String[] args) {
        String str = "198.153.1.2";
        String [] s1 = str.split("\\.");
        for (int i = 0; i < s1.length; i++) {
            System.out.println(s1[i]);
        }
    }

多个分隔符拆分

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

public class Test {
    public static void main(String[] args) {
        String str2 = "wo=he=zhangsan&zai&xuexi ";
        String [] array =str2.split("=|&");
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
 }

字符串的截取

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

String substring(int beginIndex, int endIndex)

截取部分内容

public class Test {
    public static void main(String[] args) {
        String str3 = "abcaac";
        String s4 = str3.substring(0,3);
        System.out.println(s4);//abc
    }
}

String substring(int beginIndex)

从指定索引截取到结尾

public class Test {
    public static void main(String[] args) {
        String str3 = "abcaac";
        String s4 = str3.substring(3);
        System.out.println(s4);//aac
    }

其他操作

String trim()

去掉字符串中的左右空格,保留中间空格

public class Test {
    public static void main(String[] args) {
        String str4 = " abc aac ";
        String s5 = str4.trim();
        System.out.println(s5);//abc aac 
    }

String类 练习

给定一个字符串 s ,找到它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

public class Test {
    public int firstUniqChar(String s) {
        int[] count = new int[26]; //创建一个数组
        //每遍历一个字符,就把字符对应的下标++一次
        for(int i = 0;i < s.length();i++){
            char ch = s.charAt(i);
            count[ch-'a']++;
//如果是a-a就是97-97=0,a就能在0下标位置,b-a就是97-97,b就在1下标位置,
//这个方法适用于找字符。
        }
        for(int i = 0;i < s.length();i++) {
        //再遍历一次,如果有i的下标==1,则返回i
            char ch = s.charAt(i);
            if(count[ch-'a'] == 1){
                return i;
            }
        }
        return -1;
    }

计算字符串最后一个单词的长度,单词以空格隔开

运用String类中多个库方法计算

public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();//输入
       while(in.hasNextLine()){
           int index = str.lastIndexOf(' ');//从后往前找第一个空格
           String s4 = str.substring(index+1);//截取空格后到末尾的字符串
           System.out.println(s4.length());//求字符的长度
       }
    }
相关文章
|
9天前
|
Java 索引
java基础(13)String类
本文介绍了Java中String类的多种操作方法,包括字符串拼接、获取长度、去除空格、替换、截取、分割、比较和查找字符等。
21 0
java基础(13)String类
|
6天前
|
安全 Java
String类-知识回顾①
这篇文章回顾了Java中String类的相关知识点,包括`==`操作符和`equals()`方法的区别、String类对象的不可变性及其好处、String常量池的概念,以及String对象的加法操作。文章通过代码示例详细解释了这些概念,并探讨了使用String常量池时的一些行为。
String类-知识回顾①
|
19天前
|
存储 安全 Java
Java——String类详解
String 是 Java 中的一个类,用于表示字符串,属于引用数据类型。字符串可以通过多种方式定义,如直接赋值、创建对象、传入 char 或 byte 类型数组。直接赋值会将字符串存储在串池中,复用相同的字符串以节省内存。String 类提供了丰富的方法,如比较(equals() 和 compareTo())、查找(charAt() 和 indexOf())、转换(valueOf() 和 format())、拆分(split())和截取(substring())。此外,还介绍了 StringBuilder 和 StringJoiner 类,前者用于高效拼接字符串,后者用于按指定格式拼接字符串
19 1
Java——String类详解
|
9天前
|
JavaScript 前端开发 API
javaScript中常用的String方法以及注意点总结
本文总结了JavaScript中常用的String对象的方法及其注意事项,包括大小写转换、字符获取、子字符串截取、字符串拼接、去除空格、替换、分割以及查找字符串中字符的索引等操作。提供了每种方法的使用示例代码,帮助理解它们的具体用法和差异。
22 2
|
15天前
|
安全 Java
Java StringBuffer 和 StringBuilder 类详解
在 Java 中,`StringBuffer` 和 `StringBuilder` 用于操作可变字符串,支持拼接、插入、删除等功能。两者的主要区别在于线程安全性和性能:`StringBuffer` 线程安全但较慢,适用于多线程环境;`StringBuilder` 非线程安全但更快,适合单线程环境。选择合适的类取决于具体的应用场景和性能需求。通常,在不需要线程安全的情况下,推荐使用 `StringBuilder` 以获得更好的性能。
|
15天前
|
Java 索引
Java String 类详解
Java 中的 `String` 类用于表示不可变的字符序列,是 Java 标准库 `java.lang` 包的一部分。字符串对象一旦创建,其内容不可更改,修改会生成新对象。
|
9天前
|
Java 索引
java基础扫盲-String类常用的方法
java基础扫盲-String类常用的方法
|
2月前
|
API 索引
String类下常用API
String类下常用API
36 1
|
2月前
for循环和String类下方法的一个练习题
for循环和String类下方法的一个练习题
45 1
|
2月前
|
Java API 索引
【Java基础面试二十四】、String类有哪些方法?
这篇文章列举了Java中String类的常用方法,如`charAt()`、`substring()`、`split()`、`trim()`、`indexOf()`、`lastIndexOf()`、`startsWith()`、`endsWith()`、`toUpperCase()`、`toLowerCase()`、`replaceFirst()`和`replaceAll()`,并建议面试时展示对这些方法的熟悉度,同时深入理解部分方法的源码实现。
【Java基础面试二十四】、String类有哪些方法?