Java String类的方法总结

Java String类的方法总结,第1张

Java String类的方法总结

1.Java charAt() 方法

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

使用语法:
public char charAt(int index)其中index是参数,字符的索引。该方法的返回值为指定索引位置的字符。

实例:

String s ="Jasper";

char result = s.charAt(3);

System.out.println(result);

结果为:p

2.Java compareTo()方法

compareTo() 方法用于两种方式的比较:

字符串与对象进行比较。按字典顺序比较两个字符串。语法:

int compareTo(Object o) 或 int compareTo(String anotherString)

返回值是整型,它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的长度差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束。

如果参数字符串等于此字符串,则返回值 0;如果此字符串小于字符串参数,则返回一个小于 0 的值;如果此字符串大于字符串参数,则返回一个大于 0 的值。

public static void main(String args[]) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";
 
        int result = str1.compareTo( str2 );
        System.out.println(result);
      
        result = str2.compareTo( str3 );
        System.out.println(result);
     
        result = str3.compareTo( str1 );
        System.out.println(result);
    }
以上程序执行结果为:
0
-3
3

3.Java compareToIgnoreCase() 方法

compareToIgnoreCase() 方法用于按字典顺序比较两个字符串,不考虑大小写。

语法:

int compareToIgnoreCase(String str)

str -- 要比较的字符串。

public static void main(String args[]) {
        String str1 = "STRINGS";
        String str2 = "Strings";
      
        int result = str1.compareToIgnoreCase( str2 );
        System.out.println(result);
      
    }
以上程序执行结果为:
0

4.Java concat() 方法

concat() 方法用于将指定的字符串参数连接到字符串上。

语法:

public String concat(String s)

s -- 要连接的字符串。返回值为连接后的新字符串

public static void main(String args[]) {
        String s = "日期:";
        s = s.concat("2022年1月31号");
        System.out.println(s);
    }
以上程序执行结果为:
日期:2022年1月31号

5.Java contentEquals() 方法

contentEquals() 方法用于将此字符串与指定的 StringBuffer 比较。

语法

public boolean contentEquals(StringBuffer sb)

sb -- 要与字符串比较的 StringBuffer。

如字符串与指定 StringBuffer 表示相同的字符序列,则返回 true;否则返回 false。

public static void main(String args[]) {
        String str1 = "String1";
        String str2 = "String2";
        StringBuffer str3 = new StringBuffer( "String1");

        boolean  result = str1.contentEquals( str3 );//true
        System.out.println(result);
          
        result = str2.contentEquals( str3 );//false
        System.out.println(result);
    }
以上程序执行结果为:
true
false

6.copyValueOf() 方法

有两种形式:

public static String copyValueOf(char[] data): 返回指定数组中表示该字符序列的字符串。

public static String copyValueOf(char[] data, int offset, int count): 返回指定数组中表示该字符序列的 字符串,从offset到count位。

data -- 字符数组。

offset -- 子数组的初始偏移量。

count -- 子数组的长度。

返回指定数组中表示该字符序列的字符串。

public static void main(String args[]) {
        char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'r', 'u', 'n', 'o', 'o', 'b'};
        String Str2 = "";
 
        Str2 = Str2.copyValueOf( Str1 );
        System.out.println("返回结果:" + Str2);
 
        Str2 = Str2.copyValueOf( Str1, 2, 6 );
        System.out.println("返回结果:" + Str2);
    }
以上程序执行结果为:
返回结果:hello runoob
返回结果:llo ru

7.Java endsWith() 方法

endsWith() 方法用于测试字符串是否以指定的后缀结束。

语法:

public boolean endsWith(String suffix)

suffix -- 指定的后缀。

如果参数表示的字符序列是此对象表示的字符序列的后缀,则返回 true;否则返回 false。注意,如果参数是空字符串,或者等于此 String 对象(用 equals(Object) 方法确定),则结果为 true。

public static void main(String args[]) {
        String Str = new String("你好,hello");
        boolean retVal;
 hello
        retVal = Str.endsWith( "hello" );
        System.out.println("返回值 = " + retVal );
 
        retVal = Str.endsWith( "你好" );
        System.out.println("返回值 = " + retVal );
    }
以上程序执行结果为:
返回值 = true
返回值 = false

8.Java String equals() 方法和忽略大小写的比较Java equalsIgnoreCase() 方法

equals() 方法用于将字符串与指定的对象比较。

String 类中重写了 equals() 方法用于比较两个字符串的内容是否相等。

语法:

public boolean equals(Object anObject)

anObject -- 与字符串进行比较的对象。

如果给定对象与字符串相等,则返回 true;否则返回 false。

 public static void main(String args[]) {
        String Str1 = new String("hello");
        String Str2 = Str1;
        String Str3 = new String("hi");
        String Str4 = new String("HELLO");
        boolean retVal;

        retVal = Str1.equals( Str2 );
        System.out.println("返回值 = " + retVal );

        retVal = Str1.equals( Str3 );
        System.out.println("返回值 = " + retVal );

        retVal = Str1.equalsIgnoreCase( Str4 );
        System.out.println("返回值 = " + retVal );
    }
以上程序执行结果为:
返回值 = true
返回值 = false
返回值 = true


比较==与equals
String s1 = “hello”
String s2 = “hello”
String s3 = new String("hello");
String s4 = new String("hello");
都是hello但是只有s1==s2,而s1!=s3,因为s1s2是直接创建的在公共池内,而s3s4是在对象中创建的。所以引用对象不同,因此用==不能相等

使用 == 和 equals() 比较字符串的区别。

String 中 == 比较引用地址是否相同,equals() 比较字符串的内容是否相同。

9.Java getChars() 方法

getChars() 方法将字符从字符串复制到目标字符数组。

语法:

public void getChars(int srcBegin, int srcEnd, char[] dst,  int dstBegin)

srcBegin -- 字符串中要复制的第一个字符的索引。

srcEnd -- 字符串中要复制的最后一个字符之后的索引。

dst -- 目标数组。

dstBegin -- 目标数组中的起始偏移量。

没有返回值,但可能会抛出 IndexOutOfBoundsException 异常。

public static void main(String args[]) {
        String Str1 = new String("www.github.com");
        char[] Str2 = new char[6];

        try {
            Str1.getChars(4, 10, Str2, 0);
            System.out.print("拷贝的字符串为:" );
            System.out.println(Str2 );
        } catch( Exception ex) {
            System.out.println("触发异常:截取部分超过字符串长度");
        }
    }
以上程序执行结果为:
拷贝的字符串为:github

10.Java String indexOf() 方法

indexOf() 方法有以下四种形式:

public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

语法:

public int indexOf(int ch )

或

public int indexOf(int ch, int fromIndex)

或

int indexOf(String str)

或

int indexOf(String str, int fromIndex)

ch -- 字符,Unicode 编码。

fromIndex -- 开始搜索的索引位置,第一个字符是 0 ,第二个是 1 ,以此类推。

str -- 要搜索的子字符串。

public static void main(String args[]) {
        String Str = new String("www.github.com");
        String SubStr1 = new String("github");
        String SubStr2 = new String("com");

        System.out.print("查找字符 g 第一次出现的位置 :" );
        System.out.println(Str.indexOf( 'g' ));
        System.out.print("从第2个位置查找字符 o 第一次出现的位置 :" );
        System.out.println(Str.indexOf( 'o', 2 ));
        System.out.print("子字符串 SubStr1 第一次出现的位置:" );
        System.out.println( Str.indexOf( SubStr1 ));
        System.out.print("从第8个位置开始搜索子字符串 SubStr1 第一次出现的位置 :" );
        System.out.println( Str.indexOf( SubStr1, 8 ));
        System.out.print("子字符串 SubStr2 第一次出现的位置 :" );
        System.out.println(Str.indexOf( SubStr2 ));
    }
以上程序执行结果为:
查找字符 g 第一次出现的位置 :4
从第2个位置查找字符 o 第一次出现的位置 :12
子字符串 SubStr1 第一次出现的位置:4
从第8个位置开始搜索子字符串 SubStr1 第一次出现的位置 :-1
子字符串 SubStr2 第一次出现的位置 :11

11.Java intern() 方法

intern() 方法返回字符串对象的规范化表示形式。

它遵循以下规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。

语法:

public String intern()
 public static void main(String args[]) {
        String str1 = "a";
        String str2 = "b";
        String str3 = "ab";
        String str4 = str1 + str2;
        String str5 = new String("ab");

        System.out.println(str5.equals(str3));
        System.out.println(str5 == str3);
        System.out.println(str5.intern() == str3);
        System.out.println(str5.intern() == str4);
    }
得到的结果:
true
false
true
false

在调用”ab”.intern()方法的时候会返回”ab”,但是这个方法会首先检查字符串池中是否有”ab”这个字符串,如果存在则返回这个字符串的引用,否则就将这个字符串添加到字符串池中,然会返回这个字符串的引用。

12.Java lastIndexOf() 方法

lastIndexOf() 方法有以下四种形式:

public int lastIndexOf(int ch): 返回指定字符在此字符串中最后一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

public int lastIndexOf(int ch, int fromIndex): 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索,如果此字符串中没有这样的字符,则返回 -1。

public int lastIndexOf(String str): 返回指定子字符串在此字符串中最右边出现处的索引,如果此字符串中没有这样的字符,则返回 -1。

public int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索,如果此字符串中没有这样的字符,则返回 -1。

语法:

public int lastIndexOf(int ch)

或

public int lastIndexOf(int ch, int fromIndex)

或

public int lastIndexOf(String str)

或

public int lastIndexOf(String str, int fromIndex)

ch -- 字符。

fromIndex -- 开始搜索的索引位置。

str -- 要搜索的子字符串。

  public static void main(String args[]) {
        String Str = new String("www.gotbuggg.com.com");
        String SubStr1 = new String("got");
        String SubStr2 = new String("com");

        System.out.print("查找字符 g 最后一次出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'g' ));
        System.out.print("在第14个位置之前查找字符 g 最后一次出现的位置 :" );
        System.out.println(Str.lastIndexOf( 'g', 14 ));
        System.out.print("子字符串 SubStr1 最后一次出现的位置:" );
        System.out.println( Str.lastIndexOf( SubStr1 ));
        System.out.print("在第8个位置之前搜索子字符串 SubStr1 最后一次出现的位置 :" );
        System.out.println( Str.lastIndexOf( SubStr1, 8 ));
        System.out.print("子字符串 SubStr2 最后一次出现的位置 :" );
        System.out.println(Str.indexOf( SubStr2 ));
    }
以上程序执行结果为:
查找字符 g 最后一次出现的位置 :11
在第14个位置之前查找字符 g 最后一次出现的位置 :11
子字符串 SubStr1 最后一次出现的位置:4
在第8个位置之前搜索子字符串 SubStr1 最后一次出现的位置 :4
子字符串 SubStr2 最后一次出现的位置 :13

这其中的fromIndex是在第几索引之前的最后一次出现,不是跟indexof()方法中在fromIndex之后第一次出现的位置。

13.Java matches() 方法

matches() 方法用于检测字符串是否匹配给定的正则表达式。

调用此方法的 str.matches(regex) 形式与以下表达式产生的结果完全相同:

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

在字符串匹配给定的正则表达式时,返回 true。

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.github.com");

        System.out.print("返回值 :" );
        System.out.println(Str.matches("(.*)github(.*)"));
        
        System.out.print("返回值 :" );
        System.out.println(Str.matches("(.*)google(.*)"));

        System.out.print("返回值 :" );
        System.out.println(Str.matches("www(.*)"));
    }
}
以上程序执行结果为:
返回值 :true
返回值 :false
返回值 :true

14.Java replace() 方法

replace() 方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。

语法:

public String replace(char searchChar, char newChar)   

searchChar -- 原字符。

newChar -- 新字符。

替换后生成的新字符串。

public class Main {
    public static void main(String args[]) {
        String Str = new String("Github");

        System.out.print("返回值 :" );
        System.out.println(Str.replace('G', 'T'));

        System.out.print("返回值 :" );
        System.out.println(Str.replace('u', 'D'));
    }
}
以上程序执行结果为:
返回值 :Tithub
返回值 :Githdb

15.Java split() 方法

split() 方法根据匹配给定的正则表达式来拆分字符串。

注意: . 、 $、 | 和 * 等转义字符,必须得加 \。

注意:多个分隔符,可以用 | 作为连字符。

语法:

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

regex -- 正则表达式分隔符。

limit -- 分割的份数.

public static void main(String args[]) {
        String str = new String("Welcome-to-Github");
 
        System.out.println("- 分隔符返回值 :" );
        for (String retval: str.split("-")){
            System.out.println(retval);
        }

        System.out.println("");
        System.out.println("- 分隔符设置分割份数返回值 :" );
        for (String retval: str.split("-", 2)){
            System.out.println(retval);
        }

        System.out.println("");
        String str3 = new String("acount=? and uu =? or n=?");
        System.out.println("多个分隔符返回值 :" );
        for (String retval: str3.split("and|or")){
            System.out.println(retval);
        }
}
以上程序执行结果为:
- 分隔符返回值 :
Welcome
to
Github

- 分隔符设置分割份数返回值 :
Welcome
to-Github

多个分隔符返回值 :
acount=? 
 uu =? 
 n=?

16.Java startsWith() 方法

startsWith() 方法用于检测字符串是否以指定的前缀开始。

语法:

public boolean startsWith(String prefix, int toffset)

或

public boolean startsWith(String prefix)

prefix -- 前缀。

toffset -- 字符串中开始查找的位置。

如果字符串以指定的前缀开始,则返回 true;否则返回 false。

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.Github.com");
 
        System.out.print("返回值 :" );
        System.out.println(Str.startsWith("www") );
 
        System.out.print("返回值 :" );
        System.out.println(Str.startsWith("Github") );
 
        System.out.print("返回值 :" );
        System.out.println(Str.startsWith("Github", 4) );
    }
}
以上程序执行结果为:
返回值 :true
返回值 :false
返回值 :true

17.Java subSequence() 方法

subSequence() 方法返回一个新的字符序列,它是此序列的一个子序列。

语法:

public CharSequence subSequence(int beginIndex, int endIndex)

beginIndex -- 起始索引(包括)。

endIndex -- 结束索引(不包括)。

返回一个新的字符序列,它是此序列的一个子序列

public class Test {
    public static void main(String args[]) {
         String Str = new String("www.github.com");

         System.out.print("返回值 :" );
         System.out.println(Str.subSequence(4, 10) );
    }
}
以上程序执行结果为:
返回值 :github

18.Java toCharArray() 方法

toCharArray() 方法将字符串转换为字符数组。

语法:

public char[] toCharArray
public class Test {
    public static void main(String args[]) {
        String Str = new String("www.github.com");

        System.out.print("返回值 :" );
        System.out.println( Str.toCharArray() );
    }
}
以上程序执行结果为:
返回值 :www.github.com

19. Java toString() 方法

toString() 方法返回此对象本身(它已经是一个字符串)。

语法:

public String toString()
public class Test {
    public static void main(String args[]) {
        String Str = new String("WWW.Github.COM");

        System.out.print("返回值 :" );
        System.out.println( Str.toString() );
    }
}
以上程序执行结果为:
返回值 :WWW.Github.COM

20.Java trim() 方法​​​​​​​

trim() 方法用于删除字符串的头尾空白符。

语法:

public String trim()
public class Test {
    public static void main(String args[]) {
        String Str = new String("    www.github.com    ");
        System.out.print("原始值 :" );
        System.out.println( Str );

        System.out.print("删除头尾空白 :" );
        System.out.println( Str.trim() );
    }
}
以上程序执行结果为:
原始值 :    www.github.com    
删除头尾空白 :www.github.com

21.Java valueOf() 方法

valueOf() 方法有以下几种不同形式:

valueOf(boolean b): 返回 boolean 参数的字符串表示形式。.

valueOf(char c): 返回 char 参数的字符串表示形式。

valueOf(char[] data): 返回 char 数组参数的字符串表示形式。

valueOf(char[] data, int offset, int count): 返回 char 数组参数的特定子数组的字符串表示形式。

valueOf(double d): 返回 double 参数的字符串表示形式。

valueOf(float f): 返回 float 参数的字符串表示形式。

valueOf(int i): 返回 int 参数的字符串表示形式。

valueOf(long l): 返回 long 参数的字符串表示形式。

valueOf(Object obj): 返回 Object 参数的字符串表示形式。

语法:

static String valueOf(boolean b) 

或 

static String valueOf(char c) 

或

static String valueOf(char[] data) 

或

static String valueOf(char[] data, int offset, int count) 

或

static String valueOf(double d) 

或

static String valueOf(float f) 

或

static String valueOf(int i)

或

static String valueOf(long l)

或

static String valueOf(Object obj) 
public class Test {
    public static void main(String args[]) {
        double d = 1100.00;
        boolean b = true;
        long l = 1234567890;
        char[] arr = {'g', 'i', 't', 'h', 'u', 'b' };

        System.out.println("返回值 : " + String.valueOf(d) );
        System.out.println("返回值 : " + String.valueOf(b) );
        System.out.println("返回值 : " + String.valueOf(l) );
        System.out.println("返回值 : " + String.valueOf(arr) );
    }
}
以上程序执行结果为:
返回值 : 1100.0
返回值 : true
返回值 : 1234567890
返回值 : github

22.Java String contains() 方法

contains() 方法用于判断字符串中是否包含指定的字符或字符串。

语法:

public boolean contains(CharSequence chars)

chars -- 要判断的字符或字符串。

如果包含指定的字符或字符串返回 true,否则返回 false。

public class Main {
    public static void main(String[] args) {
        String myStr = "github";
        System.out.println(myStr.contains("github"));
        System.out.println(myStr.contains("i"));
        System.out.println(myStr.contains("s"));
    }
}
以上程序执行结果为:
true
true
false

23.Java String isEmpty() 方法

​​​​​​​isEmpty() 方法用于判断字符串是否为空。

语法:

public boolean isEmpty()

如果字符串为空返回 true,否则返回 false。

字符串通过 length() 方法计算字符串长度,如果返回 0,即为空字符串。

public class Main {
    public static void main(String[] args) {
        String myStr1 = "github";  
        String myStr2 = "";        // 空字符串
        String myStr3 = "    ";    // 多个空格,length() 不为 0 
        System.out.println("myStr1 是否为空:" + myStr1.isEmpty());
        System.out.println("myStr2 是否为空:" + myStr2.isEmpty());
        System.out.println("myStr3 长度:" + myStr3.length());
        System.out.println("myStr3 是否为空:" + myStr3.isEmpty());
    }
}
以上程序执行结果为:
myStr1 是否为空:false
myStr2 是否为空:true
myStr3 长度:4
myStr3 是否为空:false

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5709680.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存