更新時間:2022-09-21 10:38:19 來源:動力節(jié)點 瀏覽1891次
Java 中提供的許多在字符串中執(zhí)行操作的方法稱為字符串函數(shù)。方法有 compare()、concat()、equals()、split()、length()、replace()、compareTo() 等。Java 中的字符串是常量,可以使用文字或Java關(guān)鍵字創(chuàng)建。字符串字面量用于提高 Java 內(nèi)存效率,關(guān)鍵字在普通內(nèi)存中創(chuàng)建 Java 字符串。字符串表示一個字符值數(shù)組,類由Serializable、Comparable、CharSequence三個接口實現(xiàn)。它以序列化或可比較的方式表示字符序列。
創(chuàng)建 String: 在 Java 中可以通過兩種方式創(chuàng)建 String 對象:
使用字符串文字: Java 中的字符串文字可以使用雙引號創(chuàng)建。
例子:
String s= “Hello World!”;
使用 new 關(guān)鍵字:可以使用關(guān)鍵字“new”創(chuàng)建 Java 字符串。
例子:
String s=new String (“Hello World!”);
字符串長度:用于獲取對象信息的方法在 Java 中稱為訪問器方法。一種與字符串相關(guān)的訪問器方法是 length () 方法。這將返回字符串對象中的字符數(shù)。
public class Exercise {
public static void main(String args[]{
String s1="Hello";
String s2="World";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}}
連接字符串:此方法返回一個新字符串,該字符串為 string1,最后結(jié)合了 string2。Concat () 方法可以與字符串文字一起使用來完成此操作。字符串也通常使用 + 運算符連接。
public class ExerciseNew {
public static void main(String args[]){
String s1="Hello";
s1=s1.concat("What is your good name?");
System.out.println(s1);
}}
創(chuàng)建格式字符串: 我們有 printf () 和 format () 方法,它們使用格式化的數(shù)字打印輸出。String 中有一個等效的類方法,稱為 format()。它返回一個字符串對象。String 對象中可用的靜態(tài) format() 方法允許創(chuàng)建可重復(fù)使用的格式化字符串,這與一次性打印語句相反。
在本節(jié)中,我們討論了 Java 中字符串函數(shù)的一些示例。
示例 #1:檢查字符串是否為空
public class IsEmptyExercise{
public static void main(String args[]){
String s1="";
String s2="Hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}}
示例 #2:修剪字符串中的空格
public class StringTrimExercise{
public static void main(String args[]){
String s1=" HelloWorld ";
System.out.println(s1+"How are you doing today"); // without trim()
System.out.println(s1.trim()+"How are you doing today"); // with trim()
}}
示例 #3:將字符串轉(zhuǎn)換為小寫
public class StringLowerExercise{
public static void main(String args[]){
String s1="HELLO HOW Are You TODAY?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
}
示例 #4:替換字符串的一部分
public class ReplaceExercise{
public static void main(String args[]){
String s1="hello how are you today";
String replaceString=s1.replace('h','t');
System.out.println(replaceString); }}
示例 #5:檢查兩個字符串是否相等
public class EqualsExercise{
public static void main(String args[]){
String s1="Hi";
String s2="Hey";
String s3="Hello";
System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
}
}
以上就是關(guān)于“Java字符串函數(shù)詳解”的介紹,大家如果想了解更多相關(guān)知識,可以關(guān)注一下Java教程,里面有更豐富的知識等著大家去學(xué)習(xí),希望對大家能夠有所幫助哦。