Java 字符串方法

java 8object oriented programmingprogramming

Java 中的字符串类有很多方法可以操作字符串,例如查找长度、格式化字符串、连接字符串等等。

以下是 Java 中的一些字符串方法 −

Sr.No方法 &描述
1char charAt(int index)
返回指定索引处的字符。
2int compareTo(Object o)
将此字符串与另一个对象进行比较。
3int compareTo(String anotherString)
按字典顺序比较两个字符串。
4int compareToIgnoreCase(String str)
按字典顺序比较两个字符串,忽略大小写差异。
5String concat(String str)
将指定字符串连接到此字符串的末尾。
6boolean contentEquals(StringBuffer sb)
当且仅当此字符串表示与指定 StringBuffer 相同的字符序列时返回 true。
7static String copyValueOf(char[] data)
返回表示指定数组中字符序列的字符串。
8static String copyValueOf(char[] data, int offset, int count)
返回表示数组中字符序列的字符串指定。
9boolean endsWith(String suffix)
测试此字符串是否以指定的后缀结尾。
10boolean equals(Object anObject)
将此字符串与指定的对象进行比较。

示例

在这里,我们将找到字符串的长度并将它们连接起来 −

public class Main {
   public static void main(String args[]) {
      String str1 = "This is ";
      String str2 = "it!";
      System.out.println("String1 = "+str1);
      System.out.println("String2 = "+str2);
      int len1 = str1.length();
      System.out.println( "String1 Length = " + len1 );
      int len2 = str2.length();
      System.out.println( "String2 Length = " + len2 );
      System.out.println("Performing Concatenation...");
      System.out.println(str1 + str2);
   }
}

输出

String1 = This is
String2 = it!
String1 Length = 8
String2 Length = 3
Performing Concatenation...
This is it!

让我们看另一个示例,其中我们将此字符串与指定的对象进行比较 −

示例

import java.util.*;
public class Demo {
   public static void main( String args[] ) {
      String Str1 = new String("This is really not immutable!!");
      String Str2 = Str1;
      String Str3 = new String("This is really not immutable!!");
      boolean retVal;
      retVal = Str1.equals( Str2 );
      System.out.println("Returned Value = " + retVal );
      retVal = Str1.equals( Str3 );
      System.out.println("Returned Value = " + retVal );
   }
}

输出

Returned Value = true
Returned Value = true

相关文章