【Java】java基础之字符串的处理

java基础之字符串处理

一、String类

如何创建字符串

  • 将字面量直接赋值给String对象:

    String greeting = "Hello";
    
  • 通过构造器创建String对象:

    public class StringDemo{
       public static void main(String args[]){
          char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b'};
          String helloString = new String(helloArray);  
          System.out.println( helloString );
       }
    }
    

**注意: ** String 类是不可改变的,所以你一旦创建了 String 对象,那它的值就无法改变了

字符串的长度:

String 类的一个访问器方法是 length() 方法,它返回字符串对象包含的字符数。

public class StringDemo {
    public static void main(String args[]) {
        String site = "Hello wolrd";
        int len = site.length();
        System.out.println( "字符串长度 : " + len );
   }
}

字符串的连接:

  • ​ 使用 ‘+’ 来连接字符串:

    "Hello," + " world" + "!"
    
  • 使用concat()方法连接字符串:

    string1.concat(string2);
    

注意: String对象是不可变的,所以连接之后的字符串其实是一个新的字符串

字符串的比较:

  • ​ 使用public int compareTo(String anotherString)方法:

    其比较过程实际上是两个字符串中相同位置上的字符按Unicode中排列顺序逐个比较的结果.如果在整个比较过程中,没有发现任何不同的地方,则表明两个字符串是完全相等的,compareTo方法返回0;如果在比较过程中,发现了不同的地方,则比较过程会停下来,这时一定是两个字符串在某个位置上不相同,如果当前字符串在这个位置上的字符大于参数中的这个位置上的字符,compareTo方法返回一个大于0的整数,否则返回一个小于0的整数.

     public class Main {
    2     public static void main(String[] args){
    3         String s1="abc";
    4         String s2="abd";
    5         System.out.println(s1.compareTo(s2));
    6     }
    7 }
    
  • 使用public boolean equals(Object anObject)方法:

    public class Main {
        public static void main(String[] args){
            String s1="abc";
            String s2=s1;
            
            String s3="abc";
            System.out.println(s1.equals(s2));//true
            System.out.println(s1.equals(s3));//true
        }
    }
    

从字符串中提取子串:

  • 使用public String substring(int beginIndex)方法

    从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回.

  • 使用public String substring(int beginIndex, int endIndex)方法

    从当前字符串中取出一个子串,该子串从beginIndex位置起至endIndex-1为结束.子串返的长度为endIndex-beginIndex.

    public class Main {
        public static void main(String[] args){
            String s1="abcdefg";
            System.out.println(s1.substring(3));//defg
            System.out.println(s1.substring(2, 3));//c [)左闭右开区间
        }
    }
    

判断字符串的前缀和后缀:

  • 判断前缀

    • 使用public boolean startsWith(String prefix)方法

      该方法用于判断当前字符串的前缀是否和参数中指定的字符串prefix一致,如果是,返回true,否则返回false.

    • 使用public boolean startsWith(String prefix, int toffset)方法

      判断当前字符串从toffset位置开始的子串的前缀是否和参数中指定的字符串prefix一致,如果是,返回true,否则返回false.

  • 后缀

    • 使用public boolean endsWith(String suffix)方法

      判断当前字符串的后缀是否和参数中指定的字符串suffix一致,如果是,返回true,否则返回false.

    public class Main {
          public static void main(String[] args){
             String s1="casvasvcdsabasdb";
             String s2="cdsab";
             //判断字串
             for(int i=0;i<s1.length();i++)
             {
                 if(s1.startsWith(s2,i)){
                     System.out.println("s2是s1的字串。"+"字串从"+i+"开始");
                     break;
                 }
             }
          }
     }
    

字符串中单个字符的查找:

  • 使用public int indexOf(int ch)方法

    查找当前字符串中某一个特定字符ch出现的位置.该方法从头向后查找,如果在字符串中找到字符ch,则返回字符ch在字符串中第一次出现的位置;如果在整个字符串中没有找到字符ch,则返回-1.

  • 使用public int indexOf(int ch, int fromIndex)方法

    从fromIndex位置向后查找,返回的仍然是字符ch在字符串第一次出现的位置.

  • 使用public int lastIndexOf(int ch)方法

    从字符串的末尾位置向前查找,返回的仍然是字符ch在字符串第一次出现的位置.

  • 使用public int lastIndexOf(int ch, int fromIndex)方法

    从fromIndex位置向前查找,返回的仍然是字符ch在字符串第一次出现的位置.

字符串中子串的查找:

  • public int indexOf(String str)
  • public int indexOf(String str, int fromIndex)
  • public int lastIndexOf(String str)
  • public int lastIndexOf(String str, int fromIndex)

字符串中字符的替换:

  • public String replace(char oldChar,char newChar)
    • ​ 该方法用字符newChar替换当前字符串中所有的字符oldChar,并返回一个新的字符串.
  • public String replaceFirst(String regex, String replacement)
    • 该方法用字符串replacement的内容替换当前字符串中遇到的第一个和字符串regex相一致的子串,并将产生的新字符串返回.
  • public String replaceAll(String regex, String replacement)
    • ​ 该方法用字符串replacement的内容替换当前字符串中遇到的所有和字符串regex相一致的子串,并将产生的新字符串返回.

字符串的拆分:

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

regex:参数是正则达式,一般情况下,分割字符串参考字符串就行,不用考虑正则表达式。
limit:分割的子字符串的个数

String str= "boo:and:foo";
//输出[boo, and:foo]
System.out.println(java.util.Arrays.toString(str.split(":",2)));
//输出[boo, and, foo]
System.out.println(java.util.Arrays.toString(str.split(":",5)));
//输出[boo, and, foo]
System.out.println(java.util.Arrays.toString(str.split(":",-2)));
//输出[b, , :and:f, , ]
System.out.println(java.util.Arrays.toString(str.split("o",5)));
//输出[b, , :and:f, , ]
System.out.println(java.util.Arrays.toString(str.split("o",-2)));
//输出[b, , :and:f]
System.out.println(java.util.Arrays.toString(str.split("o",0)));

split()方法使用的特殊情况

1)分割拆分字符串进传入的参考字符串是正则表达式中的元字符

\ ^ $ . | ? * + ( [ {

如果字符串包含$ ,用$进行分割,例如,可以使用如下3种方法,

String str= "boo$and$foo";
//使用正则表达式
System.out.println(java.util.Arrays.toString(str.split("[$]")));
//利用Pattern.quote()转义成普通字符
System.out.println(java.util.Arrays.toString(str.split(Pattern.quote("$"))));
//通过\\进行转义
System.out.println(java.util.Arrays.toString(str.split("\\$")));

如果需要保留参考字符

例如,有个字符串"0431-87534433",分割拆分之后,"-"需要保留在子字符串中:

//保留在后面子字符串中
String string = "0431-8753";
String[] parts = string.split("(?<=-)"); //?<=:正则表达式,反向肯定预查
String part1 = parts[0]; // 0431-
String part2 = parts[1]; // 8753
//保留在前面子字符串中
String string = "0431-8753";
String[] parts = string.split("(?=-)"); //?=:正则表达式,正向肯定预查
String part1 = parts[0]; // 0431
String part2 = parts[1]; // -8753

split分隔符总结

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

比如:String str = “Java string-split#test”,可以用Str.split(" |-|#")把每个字符串分开。这样就把字符串分成了3个子字符串。

String 相关方法

下面是 String 类支持的方法。

SN(序号)方法描述
1char charAt(int index) 返回指定索引处的 char 值。
2int compareTo(Object o) 把这个字符串和另一个对象比较。
3int compareTo(String anotherString) 按字典顺序比较两个字符串。
4int compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写。
5String concat(String str) 将指定字符串连接到此字符串的结尾。
6boolean contentEquals(StringBuffer sb) 当且仅当字符串与指定的StringBuffer有相同顺序的字符时候返回真。
7[static String copyValueOf(char] data) 返回指定数组中表示该字符序列的 String。
8[static String copyValueOf(char] data, int offset, int count) 返回指定数组中表示该字符序列的 String。
9boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结束。
10boolean equals(Object anObject) 将此字符串与指定的对象比较。
11boolean equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写。
12[byte] getBytes() 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
13[byte] getBytes(String charsetName) 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
14[void getChars(int srcBegin, int srcEnd, char] dst, int dstBegin) 将字符从此字符串复制到目标字符数组。
15int hashCode() 返回此字符串的哈希码。
16int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。
17int indexOf(int ch, int fromIndex) 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
18int indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引。
19int indexOf(String str, int fromIndex) 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
20String intern() 返回字符串对象的规范化表示形式。
21int lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。
22int lastIndexOf(int ch, int fromIndex) 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
23int lastIndexOf(String str) 返回指定子字符串在此字符串中最右边出现处的索引。
24int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
25int length() 返回此字符串的长度。
26boolean matches(String regex) 告知此字符串是否匹配给定的正则表达式。
27boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。
28boolean regionMatches(int toffset, String other, int ooffset, int len) 测试两个字符串区域是否相等。
29String replace(char oldChar, char newChar) 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
30String replaceAll(String regex, String replacement) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
31String replaceFirst(String regex, String replacement) 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
32[String] split(String regex) 根据给定正则表达式的匹配拆分此字符串。
33[String] split(String regex, int limit) 根据匹配给定的正则表达式来拆分此字符串。
34boolean startsWith(String prefix) 测试此字符串是否以指定的前缀开始。
35boolean startsWith(String prefix, int toffset) 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。
36CharSequence subSequence(int beginIndex, int endIndex) 返回一个新的字符序列,它是此序列的一个子序列。
37String substring(int beginIndex) 返回一个新的字符串,它是此字符串的一个子字符串。
38String substring(int beginIndex, int endIndex) 返回一个新字符串,它是此字符串的一个子字符串。
39[char] toCharArray() 将此字符串转换为一个新的字符数组。
40String toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
41String toLowerCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
42String toString() 返回此对象本身(它已经是一个字符串!)。
43String toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
44String toUpperCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
45String trim() 返回字符串的副本,忽略前导空白和尾部空白。
46static String valueOf(primitive data type x) 返回给定data type类型x参数的字符串表示形式。

注:来源菜鸟教程


二、StringBuffer 和 StringBuilder类

使用场景: 当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。

由于 StringBuilder 相较于 StringBuffer 有速度优势,所以多数情况下建议使用 StringBuilder 类。然而在应用程序要求线程安全的情况下,则必须使用 StringBuffer 类。

即: StringBuffer为线程安全

StringBuffer 方法:

以下是 StringBuffer 类支持的主要方法:

序号方法描述
1public StringBuffer append(String s) 将指定的字符串追加到此字符序列。
2public StringBuffer reverse() 将此字符序列用其反转形式取代。
3public delete(int start, int end) 移除此序列的子字符串中的字符。
4public insert(int offset, int i) 将 int 参数的字符串表示形式插入此序列中。
5replace(int start, int end, String str) 使用给定 String 中的字符替换此序列的子字符串中的字符。

下面的列表里的方法和 String 类的方法类似:

序号方法描述
1int capacity() 返回当前容量。
2char charAt(int index) 返回此序列中指定索引处的 char 值。
3void ensureCapacity(int minimumCapacity) 确保容量至少等于指定的最小值。
4void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将字符从此序列复制到目标字符数组 dst
5int indexOf(String str) 返回第一次出现的指定子字符串在该字符串中的索引。
6int indexOf(String str, int fromIndex) 从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。
7int lastIndexOf(String str) 返回最右边出现的指定子字符串在此字符串中的索引。
8int lastIndexOf(String str, int fromIndex) 返回 String 对象中子字符串最后出现的位置。
9int length() 返回长度(字符数)。
10void setCharAt(int index, char ch) 将给定索引处的字符设置为 ch
11void setLength(int newLength) 设置字符序列的长度。
12CharSequence subSequence(int start, int end) 返回一个新的字符序列,该字符序列是此序列的子序列。
13String substring(int start) 返回一个新的 String,它包含此字符序列当前所包含的字符子序列。
14String substring(int start, int end) 返回一个新的 String,它包含此序列当前所包含的字符子序列。
15String toString() 返回此序列中数据的字符串表示形式。

*声明:此博文为学习笔记,参考了菜鸟教程等网络资源,如有侵权,请私信告知!*
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值