W tym samouczku nauczymy się o napisach w języku Java, o tym, jak je tworzyć oraz o różnych metodach tworzenia ciągów za pomocą przykładów.
W Javie ciąg to sekwencja znaków. Na przykład „witaj” to ciąg znaków zawierający sekwencję znaków „h”, „e”, „l”, „l” i „o”.
Używamy podwójnych cudzysłowów do reprezentowania ciągu znaków w Javie. Na przykład,
// create a string String type = "Java programming";
Tutaj utworzyliśmy zmienną łańcuchową o nazwie type. Zmienna jest inicjalizowana za pomocą łańcucha Java Programming
.
Uwaga : Ciągi w Javie nie są prymitywne typy (jak int
, char
itp). Zamiast tego wszystkie ciągi są obiektami wstępnie zdefiniowanej klasy o nazwie String
.
Wszystkie zmienne łańcuchowe są instancjami tej String
klasy.
Przykład: Utwórz ciąg w Javie
class Main ( public static void main(String() args) ( // create strings String first = "Java"; String second = "Python"; String third = "JavaScript"; // print strings System.out.println(first); // print Java System.out.println(second); // print Python System.out.println(third); // print JavaScript ) )
W powyższym przykładzie utworzyliśmy trzy ciągi o nazwach pierwszy, drugi i trzeci. Tutaj bezpośrednio tworzymy łańcuchy, takie jak typy prymitywne.
Istnieje jednak inny sposób tworzenia napisów Java (przy użyciu new
słowa kluczowego). Dowiemy się o tym w dalszej części tego samouczka.
Operacje na łańcuchach Java
Java String udostępnia różne metody wykonywania różnych operacji na łańcuchach. Przyjrzymy się niektórym z powszechnie używanych operacji na łańcuchach.
1. Uzyskaj długość łańcucha
Aby znaleźć długość łańcucha, używamy length()
metody String. Na przykład,
class Main ( public static void main(String() args) ( // create a string String greet = "Hello! World"; System.out.println("String: " + greet); // get the length of greet int length = greet.length(); System.out.println("Length: " + length); ) )
Wynik
Ciąg: Cześć! Długość świata: 12
W powyższym przykładzie length()
metoda oblicza całkowitą liczbę znaków w ciągu i zwraca ją. Aby dowiedzieć się więcej, odwiedź stronę Java String length ().
2. Połącz dwa ciągi
Możemy połączyć dwa łańcuchy w Javie za pomocą concat()
metody. Na przykład,
class Main ( public static void main(String() args) ( // create first string String first = "Java "; System.out.println("First String: " + first); // create second String second = "Programming"; System.out.println("Second String: " + second); // join two strings String joinedString = first.concat(second); System.out.println("Joined String: " + joinedString); ) )
Wynik
Pierwszy ciąg: Java Drugi ciąg: Programowanie Połączony ciąg: Programowanie w języku Java
W powyższym przykładzie utworzyliśmy dwa ciągi o nazwach pierwszy i drugi. Zwróć uwagę na oświadczenie,
String joinedString = first.concat(second);
Tutaj concat()
metoda łączy pierwszą i drugą i przypisuje ją do zmiennej linkedString.
Możemy również połączyć dwa łańcuchy za pomocą +
operatora w Javie. Aby dowiedzieć się więcej, odwiedź witrynę Java String concat ().
3. Porównaj dwa ciągi
W Javie możemy dokonywać porównań między dwoma ciągami za pomocą equals()
metody. Na przykład,
class Main ( public static void main(String() args) ( // create 3 strings String first = "java programming"; String second = "java programming"; String third = "python programming"; // compare first and second strings boolean result1 = first.equals(second); System.out.println("Strings first and second are equal: " + result1); // compare first and third strings boolean result2 = first.equals(third); System.out.println("Strings first and third are equal: " + result2); ) )
Wynik
Ciągi pierwszy i drugi są równe: prawda Pierwsze i trzecie ciągi są równe: fałsz
W powyższym przykładzie utworzyliśmy 3 ciągi o nazwach pierwszy, drugi i trzeci. Tutaj używamy equal()
metody, aby sprawdzić, czy jeden ciąg jest równy drugiemu.
Te equals()
kontrole metoda treść strun natomiast porównując je. Aby dowiedzieć się więcej, odwiedź stronę Java String equals ().
Uwaga : możemy również porównać dwa ciągi za pomocą ==
operatora w Javie. Jednak to podejście różni się od equals()
metody. Aby dowiedzieć się więcej, odwiedź stronę Java String == vs equals ().
Metody ciągów Java
Oprócz tych wymienionych powyżej, w Javie istnieją różne metody łańcuchowe. Oto niektóre z tych metod:
Metody | Opis |
---|---|
podciąg () | zwraca podłańcuch ciągu |
zastąpić() | zastępuje określony stary znak określonym nowym znakiem |
charAt () | zwraca znak obecny w określonej lokalizacji |
getBytes () | konwertuje ciąg na tablicę bajtów |
indeks() | zwraca pozycję określonego znaku w ciągu |
porównać do() | porównuje dwa ciągi w kolejności słownikowej |
trym() | usuwa wszelkie początkowe i końcowe spacje |
format() | zwraca sformatowany ciąg |
rozdzielać() | dzieli ciąg na tablicę ciągów |
toLowerCase () | konwertuje ciąg na małe litery |
toUpperCase () | konwertuje ciąg na wielkie litery |
wartość() | zwraca ciąg znaków reprezentujący określony argument |
toCharArray () | konwertuje ciąg na char tablicę |
Znak ucieczki w ciągach Java
Znak ucieczki służy do zmiany znaczenia niektórych znaków znajdujących się w ciągu.
Załóżmy, że musimy umieścić w ciągu znaków cudzysłowy.
// include double quote String example = "This is the "String" class";
Since strings are represented by double quotes, the compiler will treat "This is the " as the string. Hence, the above code will cause an error.
To solve this issue, we use the escape character in Java. For example,
// use the escape character String example = "This is the "String " class.";
Now escape characters tell the compiler to escape double quotes and read the whole text.
Java Strings are Immutable
In Java, strings are immutable. This means, once we create a string, we cannot change that string.
To understand it more deeply, consider an example:
// create a string String example = "Hello! ";
Here, we have created a string variable named example. The variable holds the string "Hello! ".
Now suppose we want to change the string.
// add another string "World" // to the previous tring example example = example.concat(" World");
Here, we are using the concat()
method to add another string World to the previous string.
It looks like we are able to change the value of the previous string. However, this is not true
.
Let's see what has happened here,
- JVM takes the first string "Hello! "
- creates a new string by adding "World" to the first string
- assign the new string "Hello! World" to the example variable
- the first string "Hello! " remains unchanged
Creating strings using the new keyword
So far we have created strings like primitive types in Java.
Since strings in Java are objects, we can create strings using the new
keyword as well. For example,
// create a string using the new keyword String name = new String("Java String");
In the above example, we have created a string name using the new
keyword.
Here, when we create a string object, the String()
constructor is invoked. To learn more about constructor, visit Java Constructor.
Note: The String
class provides various other constructors to create strings. To learn more, visit Java String (official Java documentation).
Example: Create Java Strings using the new keyword
class Main ( public static void main(String() args) ( // create a string using new String name = new String("Java String"); System.out.println(name); // print Java String ) )
Create String using literals vs new keyword
Now that we know how strings are created using string literals and the new
keyword, let's see what is the major difference between them.
In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps in reusing the strings.
While creating strings using string literals, the value of the string is directly provided. Hence, the compiler first checks the string pool to see if the string already exists.
- Jeśli ciąg już istnieje , nowy ciąg nie jest tworzony. Zamiast tego nowe odniesienie wskazuje na istniejący ciąg.
- Jeśli ciąg nie istnieje , tworzony jest nowy ciąg.
Jednak podczas tworzenia ciągów za pomocą słowa kluczowego new wartość ciągu nie jest podawana bezpośrednio. Dlatego cały czas tworzony jest nowy ciąg.