Rumah  >  Artikel  >  Java  >  Fungsi Rentetan dalam Java

Fungsi Rentetan dalam Java

PHPz
PHPzasal
2024-08-30 15:32:46682semak imbas

Beberapa kaedah yang disediakan dalam Java untuk melaksanakan operasi dalam Strings dipanggil fungsi String. Kaedahnya ialah compare(), concat(), equals(), split(), length(), replace(), compareTo() dan sebagainya. Rentetan dalam Java adalah tetap dan dibuat menggunakan literal atau kata kunci. String literal menjadikan memori Java cekap, dan kata kunci mencipta rentetan Java dalam memori biasa. Rentetan mewakili tatasusunan nilai aksara, dan kelas dilaksanakan oleh tiga antara muka seperti antara muka Serializable, Comparable dan CharSequence. Ia mewakili urutan aksara secara bersiri atau setanding.

IKLAN Kursus Popular dalam kategori ini JAVA MASTERY - Pengkhususan | 78 Siri Kursus | 15 Ujian Olok-olok

Konsep Fungsi Rentetan dalam Java

Di bawah ialah konsep utama Fungsi Rentetan dalam java:

1. Mencipta Rentetan

Di Java, terdapat dua cara utama untuk mencipta objek String:

Menggunakan literal rentetan: Petikan berganda digunakan untuk menghasilkan literal rentetan dalam Java.

Contoh:

String s= "Hello World!";

Menggunakan kata kunci baharu: Java String boleh dibuat menggunakan “baharu”.

Contoh:

String s=new String ("Hello World!");

2. Panjang tali

Kaedah yang digunakan untuk mendapatkan maklumat tentang objek dipanggil kaedah accessor dalam Java. Satu kaedah pengakses yang berkaitan dengan rentetan ialah kaedah panjang (). Ini mengembalikan bilangan aksara dalam objek rentetan.

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());
}}

Output:

Fungsi Rentetan dalam Java

3. Rentetan penggabung

Kaedah ini mengembalikan rentetan baharu iaitu rentetan1 dengan rentetan2 digabungkan pada penghujungnya. Kaedah Concat () boleh digunakan dengan literal rentetan untuk menyelesaikannya. Rentetan juga biasanya digabungkan menggunakan operator +.

public class ExerciseNew {
public static void main(String args[]){
String s1="Hello";
s1=s1.concat("What is your good name?");
System.out.println(s1);
}}

Output:

Fungsi Rentetan dalam Java

4. Mencipta rentetan format

printf() dan format() berfungsi mengeluarkan nombor berformat. Rentetan mempunyai kaedah kelas yang serupa bernama format (). Ia menghasilkan objek String. Berbeza dengan arahan cetakan sekali, kaedah format statik () yang boleh diakses dalam objek String membenarkan pembinaan rentetan berformat yang boleh digunakan semula.

Kaedah Fungsi Rentetan dalam Java

Berikut ialah kaedah yang berbeza:

Method Description
char charAt(int index) It returns the char value of the particular index as mentioned.
int length() It returns the length of the string
static String format(String format, Object… args) It returns a string that is duly formatted.
static String format(Locale l, String format, Object… args) It returns a formatted string along with the given locale.
String substring(int beginIndex) It returns the substring, which starts from begin index.
String substring(int beginIndex, int endIndex) It returns a substring for a given start index position and ends index.
boolean contains(CharSequence s) It returns true or false after doing a match between the sequence of char values.
static String join(CharSequence delimiter, CharSequence… elements) It returns a string that is joined
static String join(CharSequence delimiter, Iterable elements) It returns a joined string, the same as above.
boolean equals(Object another) It checks the equality of the string. It does so with the given object.
boolean isEmpty() It checks if a given string is empty or not.
String concat(String str) It concatenates the specified string like the above example.
String replace(char old, char new) It replaces all occurrences of the specified old char value. With new value.
String replace(CharSequence old, CharSequence new) It replaces all occurrences of the given specified CharSequence with the new one.
static String equalsIgnoreCase(String another) It compares with another string, but It is not case-sensitive.
String[] split(String regex) It returns a split string based on matching the regex.
String[] split(String regex, int limit) It returns a split string that matches regex and limit.
String intern() It returns a string that is interned.
int indexOf(int ch) It returns the selected char value index.
int indexOf(int ch, int fromIndex) It returns the specified char value index, which starts with a given index.
int indexOf(String substring) It returns the selected substring index.
int indexOf(String substring, int fromIndex) It returns the selected substring index, which starts with a given index.
String toLowerCase() It returns a string with all chars in lowercase.
String toLowerCase(Locale l) It returns a string in lowercase with a specified locale.
String toUpperCase() It returns a string with all chars in uppercase.
String toUpperCase(Locale l)  Same as above but with a specified locale.
String trim()  It removes the starting and ending whitespaces of this string.
static String valueOf(int value) It converts another data type into a string. It is called an overloaded method.

Examples of String functions in Java

In this section, we have discussed some examples of string functions in Java.

Example #1: Check if a string is empty

Code:

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
}}

Output:

Fungsi Rentetan dalam Java

Example #2: Trim whitespaces in a string

Code:

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()
}}

Output:

Fungsi Rentetan dalam Java

Example #3: Convert a string to lowercase

Code:

public class StringLowerExercise{
public static void main(String args[]){
String s1="HELLO HOW Are You TODAY?";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
}

Output:

Fungsi Rentetan dalam Java

Example #4: Replace a part of a string

Code:

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); }}

Output:

Fungsi Rentetan dalam Java

Example #5: Check if two strings are equal

Code:

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
}
}

Output:

Fungsi Rentetan dalam Java

Conclusion

Apart from the above-mentioned characteristics, functions, and methods, there are other facts with the String class. The string class is a final class, which is why String class objects are immutable in nature. JVM reserves a special memory area for string classes; this area is called the String constant pool.

In the String library, available with Java. Lang, overriding the String references are possible, but the content or literals cannot be copied. Any number closed in double quotes is also treated as a string.

Students should test these codes in an IDE and modify them to enhance their understanding further. String manipulation is very important to know in any programming language, and developers use it daily.

Atas ialah kandungan terperinci Fungsi Rentetan dalam Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Isih Shell dalam javaArtikel seterusnya:Isih Shell dalam java