资讯详情

一些常用的String类方法

常用String类方法

文章目录

    • 常用String类方法
      • 字符串常量池
      • 1.charAt方法
      • 2.concat方法
      • 3.contains方法
      • 4.contains方法
      • 5.contentEquals(CharSequence cs)方法
      • 6.contentEquals(StringBuffer sb)方法
      • 7.endwith和startswith方法
      • 8.equals方法
      • 9.equals方法
      • 10.format方法
      • 11.getBytes方法
      • 12.hashCode方法
      • 13.indexof方法
      • 14.isBlank、isEmpty方法
      • 15.length方法
      • 16.matches方法
      • 17.regionMatch方法
      • 18.repeat方法
      • 19.replace方法
      • 20.replaceAll方法
      • 21.replaceFirst方法
      • 22.split方法
      • 23.strip方法
      • 24.subSequence方法
      • 25.substring方法
      • 26.toCharArray方法
      • 27.toUpperCase、toLowerCase方法
      • 28.srim方法
string类表示字符串,Java程序中所有的字符串文本都是这样的例子。

String两种赋值方式:

  • 直接赋值

  • 通过关键字new调用String施工方法赋值

字符串不变,创建后值不能更改。字符串是一个字符串char数组,因为String对象是不可变的,因此可以共享相同的内存地址。使用相同的字符串==比较地址的方式是相同的内存地址

相同的两串字符串有缓存和重复使用

String str = "abc";

相当于

char data[] = { 
        'a','b','c'};  String src = new String(data); 

因为字符串是用的char由于数组长度不能改变,因此字符串值是不可变的。

拼接字符串:

通过 尽量避免拼接字符串,因为使用 拼接字符串会导致大量内存垃圾,导致大量内存占用。由于字符串的特点,拼接丢弃的字符串仍然缓存在字符串常量池中,不会GC回收

当我们需要拼接字符串时,我们通常使用它(实现线程不安全),(实现线程安全)可变字符序列通过构建字符串缓冲区拼接字符串,产生的垃圾将被录用GC回收。

字符串常量池

方法区(Method Area),内存中永久存储的内容,又称永久代,加载后一直重复使用。

所有线程共享方法区

堆(heap)

一个JVM例如,只有一堆内存,可调节堆内存的大小。类加载器读取类文件后,需要将类、方法和常变放入堆内存中,以保存所有参考类型的真实信息,以方便执行器执行。

逻辑上分为三部分:

  • 新生代(Young Generation,YoungGen):垃圾回收次数小于15次的新对象
  • 老年代(Old Generation,OldGen):经过垃圾回收次数超过15次依然存活的对象
  • 永久代(Permane Generation,PermGen):垃圾回收对象、类别、方法、常量、静态修改、字符串

JDK1.8:hotspot用元空间取代了永久代,

字符串常量池仍在堆放中,常量池仍在法区运行,但方法区的实现已从永久代变为元空间。

1.charAt方法

语法:

public char charAt(int index)

返回指定位置char值。范围从0开始到长度length-1的位置。类似于数组索引

实现:

public class TestString {     public static void main(String[] args) {         String str ="锄禾日当午";         char s = str.charAt(3);         System.out.println(s);         ///结果是下标为3char值:当     } } 

参数

index - char值的索引。 第一个char值位于索引0

结果

指定索引处的字符串char值。

2.concat方法

语法:

public String concat(String str)

将指定的字符串连接到字符串的末尾。

如果参数字符串的长度为0,则返回此String对象

实现:

public class TestString { 
             public static void main(String[] args) { 
                 String str ="锄禾日当午";
        String s = str.concat("汗滴禾下土");
        System.out.println(s);
        //结果为锄禾日当午汗滴禾下土
    }
}

参数

str - 连接的字符串

结果

一个字符串,表示此对象的字符串联后跟字符串参数的字符。

3.contains方法

语法:

public boolean contains(CharSequence s)

当且仅当此字符串包含指定的char值序列时,才返回true

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str ="锄禾日当午";
        boolean s = str.contains("日");
        System.out.println(s);
        //结果为true
    }
}

参数

s -要搜索的字符序列

结果

如果此字符串包含s,则返回true,否则返回false。

4.contains方法

语法:

public boolean contains(CharSequence s)

当且仅当此字符串包含指定的char值序列时,才返回true

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str ="锄禾日当午";
        boolean s = str.contains("日");
        System.out.println(s);
        //结果为true
    }
}

参数

s -要搜索的字符序列

结果

如果此字符串包含s,则返回true,否则返回false

5.contentEquals(CharSequence cs)方法

语法:

public boolean contentEquals(CharSequence cs)

当且仅当此字符串与指定的char值序列相同时,才返回true,注意,如果CharSequence是StringBuffer则该方法会对其进行同步。

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="锄禾日当午";
        boolean s1 = str1.contentEquals("锄禾日当午");
        boolean s2 = str1.contentEquals("锄禾");
        System.out.println(s1);//结果为true
        System.out.println(s2);//结果为false
    }
}

参数

cs -要比较的String字符串序列

结果

如果此字符串表示与指定序列相同的char值序列,则返回true,否则返回false

6.contentEquals(StringBuffer sb)方法

语法:

public boolean content(StringBuffer sb)

将此字符串与指定的StringBuffer比较,此方法在StringBuffer上同步

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="锄禾日当午";
        String str2 ="锄禾日当";
        StringBuffer str3 = new StringBuffer( "锄禾日当午");

        boolean result1 = str1.contentEquals( str3 );
        System.out.println(result1);

        boolean result2 = str2.contentEquals( str3 );
        System.out.println(result2);
    }
}

参数

sb -用StringBuffer来比较的字符串序列

结果

如果此字符串表示与指定序列相同的char值序列,则返回true,否则返回false

7.endwith和startswith方法

语法:

public boolean endsWith(String suffix)

public boolean startsWith(String prefix)

测试此字符串是否以指定的后缀结尾。

测试此字符串是否以指定的前缀开头。

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="锄禾日当午";
        boolean s1 = str1.endsWith("当");
        boolean s2 = str1.startsWith("锄");
        System.out.println(s1);//结果为false
        System.out.println(s2);//结果为true
    }
}

参数

suffix -后缀

prefix -前缀

结果

如果参数表示的字符序列是该对象表示的字符序列的后缀或前缀,则返回true,否则返回false,注意,如果参数是空字符串或等于该String由确定的对象equals(object)方法

8.equals方法

语法:

public boolean equals(Object anObject)

将此字符串与指定的对象进行比较。 当且仅当参数不是null且是String对象表示与此对象相同的字符序列时,结果为true

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="锄禾日当午";
        String str2 = new String("锄禾");
        System.out.println(str1.equals(str2));
        //结果为false
    }
}

参数

anObject -对比String的对象

结果

如果给定的对象表示String相当于这个字符串,则返回true,否则返回false

9.equals方法

语法:

public boolean equalsIgnoreCase(String anotherString)

将此String与另一个String比较,忽略了大小写。如果两个字符串具有相同的长度并且两个字符串中的相应字符等于忽略大小写,则认为它们是相等的忽略大小写。

如果至少满足下列条件之一,则两个字符c1c2被视为相同的忽略大小写:

  • 两个字符相同(由==比较)
  • 在每个字符上调用Character.toLowerCase(Character.toUpperCase(char))会产生相同的结果

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="i love fish";
        String str2 ="I Love FISH";
        System.out.println(str1.equalsIgnoreCase(str2));
    }
}

参数

antherString -对比String

结果

如果参数不是null并且代表等效的String(忽略大小写),则返回true,否则返回false

10.format方法

语法:

public byte[] getBytes()

使用指定的格式字符串和参数返回格式化字符串。

始终使用的语言环境是由Locale.getDefault(Locale.Category)返回的语言环境,其中指定了FORMAT类别。

重载方法

format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。 format(Locale locale, String format, Object… args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串。

参数

antherString -对比String

结果

格式化的字符串

异常

IllegalFormatException - 如果格式字符串包含非法语法,格式说明符与给定参数不兼容,给定格式字符串的参数不足或其他非法条件。 有关所有可能的格式错误的说明,请参阅formatter类规范的Details部分。

11.getBytes方法

语法

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

使用指定的字符集将此String编码为字节序列,将结果存储到新的字节数组中。

语法

public byte[] getBytes(Charset charset)

使用给定的charset将此String编码为字节序列,将结果存储到新的字节数组中。

12.hashCode方法

语法

public int hashCode()

返回此字符的哈希吗。String对象的哈希码计算为:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

使用int算术,其中是[ i ] 是字符串的第 i 个字符,n是字符串的长度,^表示取幂。(空字符串的哈希值为零)

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="i";
        System.out.println(str1.hashCode());
        //结果是105
    }
}

重写

hashCode在类Object

结果

此对象的哈希码值

13.indexof方法

语法:

public int indexOf(int ch)

返回指定字符第一次出现的字符串中的索引。

public int indexOf(int ch, int fromIndex)

从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。

public int indexOf(String str)

返回指定子字符串第一次出现的字符串中的索引。

public int indexOf(String str, int fromIndex)

从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。

lastIndexOf

public int lastindexOf(int ch)

返回指定字符最后一次出现的字符串中的索引。

public int lastindexOf(int ch, int fromIndex)

从指定的索引处开始,返回指定子字符串最后一次出现的字符串中的索引。

public int lastindexOf(String str)

返回指定子字符串最后一次出现的字符串中的索引。

public int lastindexOf(String str, int fromIndex)

从指定的索引处开始,返回指定子字符串最后一次出现的字符串中的索引。

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str ="123456789";
        System.out.println(str.indexOf("3"));
        //输出结果为2
        System.out.println(str.indexOf("3",1));
        //输出结果为2
        
        //查找Unicode格式5-53
        System.out.println(str.indexOf(53));
        //输出结果为4
        System.out.println(str.indexOf(53,1));
        //输出结果为4
    }
}

参数

ch -字符

fromIndex-从中开始搜索的索引

str-要搜索的子字符串

14.isBlank、isEmpty方法

语法:

public boolean isBlank()

如果字符串为空或仅包含 white space个代码点,则返回 true ,否则 false

public boolean isEmpty()

length()0 ,返回true,否则返回false

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str ="";
        System.out.println(str.isBlank());//true
        System.out.println(str.isEmpty());//true
    }
}

15.length方法

语法:

public int length()

返回此字符串的长度。 长度等于字符串中的Unicode code units的数量。返回数组长度

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str ="123456789";
        System.out.println(str.length());
        //结果为9
    }
}

16.matches方法

语法:

public boolean matches(String regex)

判断此字符串是否与给定的正则表达式匹配

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str ="i love fish";
        System.out.println(str.matches("(.*)love(.*)"));//true
        System.out.println(str.matches("(.*)LOVE(.*)"));//false
    }
}

参数:

regex-要与此字符串匹配的正则表达式

结果:

当且仅当此字符串与给定的正则表达式匹配是为true

17.regionMatch方法

语法:

public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

public boolean regionMatches(int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="i love fish";
        String str2 ="love";
        String str3 ="LOVE";
        System.out.println(str1.regionMatches(2,str2,0,4));//true
        System.out.println(str1.regionMatches(2,str3,0,4));//false
        System.out.println(str1.regionMatches(true,2,str3,0,4));//true
    }
}

参数:

ignoreCase-如果是true,请在比较时忽略大小写。

toffset-从字符串参数toffset区域的下标开始比较

other-字符串参数(要比较的字符串)

ooffset-从字符串参数ooffset区域的下标开始比较

len-要比较的字符数

结果:

如果此字符串的指定子区域与字符串参数的指定子区域匹配,为true,否则为false。匹配是精确匹配还是不区分大小写取决于ignoreCase参数

18.repeat方法

语法:

public String repeat(int count)

返回一个字符串,其值为此字符串的串联重复次数。如果此字符串为空或为次数为零,则返回空字符串。

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="123";
        String str2 ="";
        System.out.println(str1.repeat(3));//输出结果123123123
        System.out.println(str2.repeat(3));//输出结果空
    }
}

参数:

count-重复次数

结果

由此字符串组成的字符串重复 count次,如果此字符串为空或count为零,则为空字符串

异常

IllegalArgumentException - 如果 count为负数。

19.replace方法

语法:

public String replace(char oldChar, char newChar)

将新的字符串newChar替换掉原来的字符串oldChar,并返回新的字符串

public String replace(CharSequence target, CharSequence replacement)

将此字符串中与文字目标序列匹配的每个子字符串替换为指定的文字替换序列。 替换从字符串的开头到结尾,例如,在字符串“aaa”中将“aa”替换为“b”将导致“ba”而不是“ab”。

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="1234567891";
        System.out.println(str1.replace('1','A'));//结果为A23456789A
        String str2 ="123456789123";
        System.out.println(str2.replace("123","321"));//结果为321456789321
    }
}

参数:

newChar-用于替换的单个字符

oldChar-被替换的单个字符

target-用于替换的字符串

replacement-被替换的字符串

结果:

通过匹配替换字符串,形成新的字符串

20.replaceAll方法

语法:

public String replaceAll(String regex, String replacement)

正则表达式替换目标位置的字符串,全部替换

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str1 ="0010101";
        System.out.println(str1.replaceAll("0","1"));输出结果1111111
    }
}

参数:

regex-与此字符串匹配的正则表达式

replacement-被替换的每个匹配的字符串

结果:

如果匹配替换所有字符串,形成新的字符串

异常

PatternSyntaxException - 如果正则表达式的语法无效

21.replaceFirst方法

语法:

public String replaceFirst(String regex, String replacement)

正则表达式替换目标位置的第一个字符串

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str2 ="0010101";
        System.out.println(str2.replaceFirst("0","1"));输出结果1010101
    }
}

参数:

regex-与此字符串匹配的正则表达式

replacement-被替换的每个匹配的字符串

结果:

如果匹配替换第一个字符串,形成新的字符串

异常

PatternSyntaxException - 如果正则表达式的语法无效

22.split方法

语法:

public String[] split(String regex)

将字符串通过regex匹配项查分为不同的字符串,形成新的字符串数组

public String[] split(String regex,int limit)

将字符串通过regex匹配项查分为不同的字符串,形成新的字符串数组,limit限制拆分的次数,0为无限制

limit参数控制应用模式的次数,因此会影响结果数组的长度。

  • 如果限制为正,则模式将应用最多限制 - 1次,数组的长度不会超过限制 ,并且数组的最后一个条目将包含超出最后一个匹配分隔符的所有输入。
  • 如果限制为零,则模式将尽可能多地应用,数组可以具有任何长度,并且将丢弃尾随空字符串。
  • 如果限制为负,则模式将尽可能多地应用,并且数组可以具有任何长度。

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = "i love fish,i love book";
        String[] s = str.split(" ",4);
        for (int i = 0; i <s.length ; i++) { 
        
            System.out.println(s[i]);
        }//输出结果
        i
        love
        fish,i
        love book
        String str = "i love fish,i love book";
        String[] s = str.split(" ",0);
        for (int i = 0; i <s.length ; i++) { 
        
            System.out.println(s[i]);
        }//输出结果
        i
        love
        fish,i
        love
        book
        String str = "i love fish,i love book";
        String[] s = str.split(" ",-2);
        for (int i = 0; i <s.length ; i++) { 
        
            System.out.println(s[i]);
        }//输出结果
        i
        love
        fish,i
        love
        book
    }
}

参数:

regex-分割正则表达式

limit-分割正则表达式

结果

通过在给定正则表达式的匹配项周围拆分此字符串计算的字符串数组

异常

PatternSyntaxException - 如果正则表达式的语法无效

23.strip方法

语法:

public String strip()

返回一个字符串,删除前面和后面的所有空格的字符串

public String stripLeading()

返回一个字符串,删除前面所有空格的字符串

public String striptrailing()

返回一个字符串,删除后面所有空格的字符串

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = " i love fish,i love book ";
        System.out.println(str.strip());        //输出结果i love fish,i love book
        System.out.println(str.stripLeading()); //输出结果i love fish,i love book 
        System.out.println(str.stripTrailing());//输出结果 i love fish,i love book
    }
}

结果:

返回一个删除前面和后面空格的字符串

24.subSequence方法

接口方法

语法:

public CharSequence subSequence(int beginIndex, int endIndex)

返回一个从开始下标和结束下标截取的子字符串

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = "i love fish,i love book";
        System.out.println(str.subSequence(2,11));//输出结果love fish
    }
}

参数

beginIndex - 起始索引。

endIndex - 结束索引。

结果

指定的子字符串

异常

IndexOutOfBoundsException - 如果 beginIndexendIndex为负数,如果 endIndex大于 length() ,或者 beginIndex大于 endIndex

25.substring方法

语法:

public String substring(int beginIndex)

返回一个从开始下标截取到字符串尾部的子字符串

public String substring(int beginIndex, int endIndex)

返回一个从开始下标和结束下标-1处截取的子字符串

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = "i love fish,i love book";
        System.out.println(str.substring(2));//输出结果love fish,i love book
        System.out.println(str.substring(2,8));//输出结果love f
    }
}

参数

beginIndex - 起始索引。

endIndex - 结束索引。

结果

指定的子字符串

异常

IndexOutOfBoundsException - 如果 beginIndexendIndex为负数,如果 endIndex大于 length() ,或者 beginIndex大于 endIndex

26.toCharArray方法

语法:

public char[] toCharArray()

将字符串转换为新的字符数组

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = "i love fish";
        char[] s = str.toCharArray();
        for (int i = 0; i <s.length ; i++) { 
        
            System.out.print(s[i]+",");
        }//输出结果i, ,l,o,v,e, ,f,i,s,h,
    }
}

结果

新的字符数组,长度为字符串的长度,内容初始化为包含此字符串表示的字符序列。

27.toUpperCase、toLowerCase方法

语法:

public String toUpperCase()

将字符串的所有字符转换为大写

public String toLowerCase()

将字符串的所有字符转换为小写

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = "i love fish";
        System.out.println(str.toUpperCase());//输出结果为I LOVE FISH
        String str1 = "i LOVE fish";
        System.out.println(str1.toLowerCase());//输出结果为i love fish
    }
}

结果

返回转换后的子字符串

28.srim方法

语法:

public String srim()

返回一个字符串,删除前面和后面的所有空格的字符串

实现:

public class TestString { 
        
    public static void main(String[] args) { 
        
        String str = " i LOVE fish ";
        System.out.println(str.trim());//输出结果为i LOVE fish
    }
}

结果:

返回一个删除前面和后面空格的字符串

1、trim()方法不足之处

trim()早在Java早期就存在,当时Unicode还没有完全发展到我们今天广泛使用的标准。

trim()方法移除字符串两侧的空白字符(空格、tab键、换行符)

支持Unicode的空白字符的判断应该使用isWhitespace(int)。

此外,开发人员无法专门删除缩进空白或专门删除尾随空白。

简单得说就是,trim()方法无法删除掉Unicode空白字符,但用Character.isWhitespace©方法可以判断出来。

2、strip()方法

JAVA11(JDK11)中的strip()方法,适用于字符首尾空白是Unicode空白字符的情况,通过一段代码来具体看一下,

public static void main(String[] args) { String s = “\t abc \n”; System.out.println( “abc”.equals(s.trim()));//true System.out.println(“abc”.equals(s.trim()));//true Character c = ‘\u2000’; String s1 = c + “abc” + c; System.out.println(Character.isWhitespace©);//true System.out.println(s1.equals(s1.trim()));//true System.out.println(“abc”.equals(s1.strip()));//true } 上面输出结果都是true, Character c = ‘\u2000’;中’\u2000’就是Unicdoe空白字符。 ———————————————— 版权声明:本文为CSDN博主「李昊轩的博客」的原创文章,遵循 CC 4.0 BY-NC-SA 版权协议,转载请附上原文出处链接及本声明。 String str = " i LOVE fish "; System.out.println(str.trim());//输出结果为i LOVE fish } }


结果:

返回一个删除前面和后面空格的字符串



1、trim()方法不足之处

trim()早在Java早期就存在,当时Unicode还没有完全发展到我们今天广泛使用的标准。

trim()方法移除字符串两侧的空白字符(空格、tab键、换行符)

支持Unicode的空白字符的判断应该使用isWhitespace(int)。

此外,开发人员无法专门删除缩进空白或专门删除尾随空白。

简单得说就是,trim()方法无法删除掉Unicode空白字符,但用Character.isWhitespace©方法可以判断出来。

2、strip()方法

JAVA11(JDK11)中的strip()方法,适用于字符首尾空白是Unicode空白字符的情况,通过一段代码来具体看一下,

public static void main(String[] args) {
String s = “\t abc \n”;
System.out.println( “abc”.equals(s.trim()));//true
System.out.println(“abc”.equals(s.trim()));//true
Character c = ‘\u2000’;
String s1 = c + “abc” + c;
System.out.println(Character.isWhitespace©);//true
System.out.println(s1.equals(s1.trim()));//true
System.out.println(“abc”.equals(s1.strip()));//true
}
上面输出结果都是true, Character c = ‘\u2000’;中’\u2000’就是Unicdoe空白字符。
————————————————
版权声明:本文为CSDN博主「李昊轩的博客」的原创文章,遵循 CC 4.0 BY-NC-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_33709508/article/details/102811412

标签: srim2嵌入式微差压传感器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台