字符串类在Java中有很多方法可以处理字符串,查找长度,格式化字符串,连接等。
以下是Java中的一些字符串方法-
| 序号 | 方法与说明 | 
|---|---|
| 1 | char charAt(int index) 返回指定索引处的字符。  | 
| 2 | int compareTo(Object o) 将此字符串与另一个对象进行比较。  | 
| 3 | int compareTo(String anotherString)按 字典顺序比较两个字符串。  | 
| 4 | int compareToIgnoreCase(String str)按 字典顺序比较两个字符串,忽略大小写差异。  | 
| 5 | String concat(String str) 将指定的字符串连接到该字符串的末尾。  | 
| 6 | boolean contentEquals(StringBuffer sb) 当且仅当此String表示与指定StringBuffer相同的字符序列时,才返回true。  | 
| 7 | static String copyValueOf(char [] data) 返回一个String,它表示指定数组中的字符序列。  | 
| 8 | static String copyValueOf(char [] data,int offset,int count) 返回一个String,它表示指定数组中的字符序列。  | 
| 9 | boolean EndsWith(String suffix) 测试此字符串是否以指定的后缀结尾。  | 
| 10 | boolean 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