• JAVASE(复习)——API(String)


    public final class String

    final修饰,一旦创建了 String 对象,那它的值就无法改变了

    一,创建字符串

    String str1 = new String("aaa");

    如果单纯这样的语句毫无疑问创建了两个对象。 

    1. String str = "aaa";
    2. String str1 = new String("aaa");

    如果第二种方式需要注意:

    第二句创建方式则创建了一个对象,因为aaa是从字符串常量池中取出来的。

    二、字符串String长度获取

    和数组一样的方式:

    1. String str = "aaa";
    2. int len = str.length;

    三、字符串String方法

    (1)charAt() 方法:charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1

    1. public class Test {
    2. public static void main(String args[]) {
    3. String s = "abcd";
    4. char result = s.charAt(1);
    5. System.out.println(result);//结果是:b
    6. }
    7. }

    2)compareTo() 方法两种方式的比较:字符串对象进行比较,按字典顺序比较两个字符串。

    1. public class Test {
    2. public static void main(String args[]) {
    3. String str1 = "abc";
    4. String str2 = "abc";
    5. String str3 = "abc123";
    6. int result = str1.compareTo( str2 );
    7. System.out.println(result);// 结果是0,两个字符串内容相同
    8. result = str2.compareTo( str3 );
    9. System.out.println(result);//结果是-3.str2比str3短,输出是负数
    10. result = str3.compareTo( str1 );
    11. System.out.println(result);// 结果是3,str3比str1长,输出是正数
    12. }
    13. }

    (3) split() 方法:才分字符串

    • 注意: . 、 $ | 和 * 等转义字符,必须得加 \\
    • 注意:多个分隔符,可以用 | 作为连字符。
    1. public class Test {
    2. public static void main(String args[]) {
    3. String str3 = new String("acount=? and uu =? or n=?");
    4. System.out.println("多个分隔符返回值 :" );
    5. for (String retval: str3.split("and|or")){
    6. System.out.println(retval);
    7. //多个分隔符返回值 :
    8. //acount=?
    9. //uu =?
    10. //n=?
    11. }
    12. }
    13. }

    (4)substring() 方法:返回字符串的子字符串

    1. public class RunoobTest {
    2. public static void main(String args[]) {
    3. String Str = new String("abc def");
    4. System.out.print("返回值 :" );
    5. System.out.println(Str.substring(1, 5));
    6. //结果:c d
    7. //从第1个后面截到第5个前面,也就是索引2,3,4
    8. }
    9. }

    (5)substring() 方法:返回字符串的子字符串

    1. public static void main(String[] args) {
    2. //将字符串解析为int类型
    3. String str = "100";
    4. //方式1
    5. Integer i = Integer.valueOf(str);
    6. int num = i.intValue();
    7. //方式2
    8. int number = Integer.parseInt(str);
    9. }

    (6)字符串替换:replace("A","B")

    字母B替换字母A

    1. String s = "ABC";
    2. String result = s.replace("A","B");

  • 相关阅读:
    PAT甲级:1040 Longest Symmetric String
    学node 之前你要知道这些
    c++的类和对象(中):默认成员函数与运算符重载(重难点!!)
    整合MyBatis-plus
    【MATLAB】矩阵的基本运算
    webui automatic1111上可以跑stable diffusion 3的方法
    PyQt 信号与槽之多窗口数据传递(Python)
    40 _ 初识动态规划:如何巧妙解决“双十一”购物时的凑单问题?
    【JavaEE---复习】一、.Spring的Ioc和DI
    微视网媒:新媒体时代的宣传与营销新范式
  • 原文地址:https://blog.csdn.net/weixin_45754865/article/details/127754249