Inhaltsverzeichnis
Concept of String Functions in Java
1. Creating String
2. String length
3. Concatenating string
4. Creating a format string
Methods of String Functions in Java
Examples of String functions in Java
Example #1: Check if a string is empty
Example #2: Trim whitespaces in a string
Example #3: Convert a string to lowercase
Example #4: Replace a part of a string
Example #5: Check if two strings are equal
Conclusion
Heim Java javaLernprogramm String-Funktionen in Java

String-Funktionen in Java

Aug 30, 2024 pm 03:32 PM
java

A number of methods provided in Java to perform operations in Strings are called String functions. The methods are compare(), concat(), equals(), split(), length(), replace(), compareTo() and so on. Strings in Java are constant and created using a literal or keyword. String literal makes Java memory efficient, and the keyword creates a Java string in normal memory. The string represents an array of character values, and the class is implemented by three interfaces such as Serializable, Comparable, and CharSequence interfaces. It represents the sequence of characters in a serialized or comparable manner.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Concept of String Functions in Java

Below are the main concepts of String Functions in java:

1. Creating String

In Java, there are two primary ways to create a String object:

Using a string literal: Double quotes are used to produce a string literal in Java.

Example:

String s= "Hello World!";
Nach dem Login kopieren

Using the new keyword: Java String can be created using “new”.

Example:

String s=new String ("Hello World!");
Nach dem Login kopieren

2. String length

Methods that are used to get information about an object are called accessor methods in Java. One such accessor method related to strings is the length () method. This returns the number of characters in the string object.

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());
}}
Nach dem Login kopieren

Output:

String-Funktionen in Java

3. Concatenating string

This method returns a new string which is string1 with string2 combined at the end. Concat () method can be used with string literals to get this done. Strings are also commonly concatenated using the + 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);
}}
Nach dem Login kopieren

Output:

String-Funktionen in Java

4. Creating a format string

The printf() and format() functions output formatted numbers. The string has a similar class method named format (). It yields a String object. In contrast to the one-time print command, the static format () method accessible in the String object permits the construction of a formatted string that may be reused.

Methods of String Functions in Java

The following are the different methods:

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
}}
Nach dem Login kopieren

Output:

String-Funktionen in 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()
}}
Nach dem Login kopieren

Output:

String-Funktionen in 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);}
}
Nach dem Login kopieren

Output:

String-Funktionen in 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); }}
Nach dem Login kopieren

Output:

String-Funktionen in 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
}
}
Nach dem Login kopieren

Output:

String-Funktionen in 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.

Das obige ist der detaillierte Inhalt vonString-Funktionen in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

<🎜>: Bubble Gum Simulator Infinity - So erhalten und verwenden Sie Royal Keys
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusionssystem, erklärt
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Flüstern des Hexenbaum
3 Wochen vor By 尊渡假赌尊渡假赌尊渡假赌

Heiße Werkzeuge

Notepad++7.3.1

Notepad++7.3.1

Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version

SublimeText3 chinesische Version

Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1

Senden Sie Studio 13.0.1

Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6

Dreamweaver CS6

Visuelle Webentwicklungstools

SublimeText3 Mac-Version

SublimeText3 Mac-Version

Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

Java-Tutorial
1666
14
PHP-Tutorial
1273
29
C#-Tutorial
1253
24
Brechen oder aus Java 8 Stream foreach zurückkehren? Brechen oder aus Java 8 Stream foreach zurückkehren? Feb 07, 2025 pm 12:09 PM

Java 8 führt die Stream -API ein und bietet eine leistungsstarke und ausdrucksstarke Möglichkeit, Datensammlungen zu verarbeiten. Eine häufige Frage bei der Verwendung von Stream lautet jedoch: Wie kann man von einem Foreach -Betrieb brechen oder zurückkehren? Herkömmliche Schleifen ermöglichen eine frühzeitige Unterbrechung oder Rückkehr, aber die Stream's foreach -Methode unterstützt diese Methode nicht direkt. In diesem Artikel werden die Gründe erläutert und alternative Methoden zur Implementierung vorzeitiger Beendigung in Strahlverarbeitungssystemen erforscht. Weitere Lektüre: Java Stream API -Verbesserungen Stream foreach verstehen Die Foreach -Methode ist ein Terminalbetrieb, der einen Vorgang für jedes Element im Stream ausführt. Seine Designabsicht ist

PHP: Eine Schlüsselsprache für die Webentwicklung PHP: Eine Schlüsselsprache für die Webentwicklung Apr 13, 2025 am 12:08 AM

PHP ist eine Skriptsprache, die auf der Serverseite weit verbreitet ist und insbesondere für die Webentwicklung geeignet ist. 1.PHP kann HTML einbetten, HTTP -Anforderungen und Antworten verarbeiten und eine Vielzahl von Datenbanken unterstützt. 2.PHP wird verwendet, um dynamische Webinhalte, Prozessformdaten, Zugriffsdatenbanken usw. mit starker Community -Unterstützung und Open -Source -Ressourcen zu generieren. 3. PHP ist eine interpretierte Sprache, und der Ausführungsprozess umfasst lexikalische Analyse, grammatikalische Analyse, Zusammenstellung und Ausführung. 4.PHP kann mit MySQL für erweiterte Anwendungen wie Benutzerregistrierungssysteme kombiniert werden. 5. Beim Debuggen von PHP können Sie Funktionen wie error_reporting () und var_dump () verwenden. 6. Optimieren Sie den PHP-Code, um Caching-Mechanismen zu verwenden, Datenbankabfragen zu optimieren und integrierte Funktionen zu verwenden. 7

PHP vs. Python: Verständnis der Unterschiede PHP vs. Python: Verständnis der Unterschiede Apr 11, 2025 am 12:15 AM

PHP und Python haben jeweils ihre eigenen Vorteile, und die Wahl sollte auf Projektanforderungen beruhen. 1.PHP eignet sich für die Webentwicklung mit einfacher Syntax und hoher Ausführungseffizienz. 2. Python eignet sich für Datenwissenschaft und maschinelles Lernen mit präziser Syntax und reichhaltigen Bibliotheken.

Php gegen andere Sprachen: Ein Vergleich Php gegen andere Sprachen: Ein Vergleich Apr 13, 2025 am 12:19 AM

PHP eignet sich für die Webentwicklung, insbesondere für die schnelle Entwicklung und Verarbeitung dynamischer Inhalte, ist jedoch nicht gut in Anwendungen auf Datenwissenschaft und Unternehmensebene. Im Vergleich zu Python hat PHP mehr Vorteile in der Webentwicklung, ist aber nicht so gut wie Python im Bereich der Datenwissenschaft. Im Vergleich zu Java wird PHP in Anwendungen auf Unternehmensebene schlechter, ist jedoch flexibler in der Webentwicklung. Im Vergleich zu JavaScript ist PHP in der Back-End-Entwicklung präziser, ist jedoch in der Front-End-Entwicklung nicht so gut wie JavaScript.

PHP vs. Python: Kernmerkmale und Funktionen PHP vs. Python: Kernmerkmale und Funktionen Apr 13, 2025 am 12:16 AM

PHP und Python haben jeweils ihre eigenen Vorteile und eignen sich für verschiedene Szenarien. 1.PHP ist für die Webentwicklung geeignet und bietet integrierte Webserver und reichhaltige Funktionsbibliotheken. 2. Python eignet sich für Datenwissenschaft und maschinelles Lernen mit prägnanter Syntax und einer leistungsstarken Standardbibliothek. Bei der Auswahl sollte anhand der Projektanforderungen festgelegt werden.

Auswirkungen von PHP: Webentwicklung und darüber hinaus Auswirkungen von PHP: Webentwicklung und darüber hinaus Apr 18, 2025 am 12:10 AM

PhPhas significantantyPactedWebDevelopmentAndendendsbeyondit.1) iTpowersMAjorPlatforms-LikewordpressandExcelsInDatabaseInteractions.2) php'SadaptabilityAllowStoscaleForLargeApplicationsfraMe-Linien-Linien-Linien-Linienkripte

PHP: Die Grundlage vieler Websites PHP: Die Grundlage vieler Websites Apr 13, 2025 am 12:07 AM

Die Gründe, warum PHP für viele Websites der bevorzugte Technologie -Stack ist, umfassen die Benutzerfreundlichkeit, die starke Unterstützung der Community und die weit verbreitete Verwendung. 1) Einfach zu erlernen und zu bedienen, geeignet für Anfänger. 2) eine riesige Entwicklergemeinschaft und eine reichhaltige Ressourcen haben. 3) in WordPress, Drupal und anderen Plattformen häufig verwendet. 4) Integrieren Sie eng in Webserver, um die Entwicklung der Entwicklung zu vereinfachen.

PHP vs. Python: Anwendungsfälle und Anwendungen PHP vs. Python: Anwendungsfälle und Anwendungen Apr 17, 2025 am 12:23 AM

PHP eignet sich für Webentwicklungs- und Content -Management -Systeme, und Python eignet sich für Datenwissenschafts-, maschinelles Lernen- und Automatisierungsskripte. 1.PHP hat eine gute Leistung beim Erstellen von schnellen und skalierbaren Websites und Anwendungen und wird üblicherweise in CMS wie WordPress verwendet. 2. Python hat sich in den Bereichen Datenwissenschaft und maschinelles Lernen mit reichen Bibliotheken wie Numpy und TensorFlow übertrifft.

See all articles