Java字符串方法
字符串类在Java中有很多方法可以处理字符串,查找长度,格式化字符串,连接等。
以下是Java中的一些字符串方法-
返回指定索引处的字符。
将此字符串与另一个对象进行比较。
字典顺序比较两个字符串。
字典顺序比较两个字符串,忽略大小写差异。
将指定的字符串连接到该字符串的末尾。
当且仅当此String表示与指定StringBuffer相同的字符序列时,才返回true。
返回一个String,它表示指定数组中的字符序列。
返回一个String,它表示指定数组中的字符序列。
测试此字符串是否以指定的后缀结尾。
将此字符串与指定对象进行比较。
示例
在这里,我们将找到字符串的长度并将其连接-
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