top of page

Programming Skills with Effective String Manipulation

String manipulation in java involves various operations to modify, extract, or manipulate the content of strings. Java provides a rich set of methods and classes for working with strings. Here are some common string manipulation operations in Java:

  1. Concatenation:

Combining two or more Strings together using the ‘+’ operator or the ‘concat’ method.

String str1 = "Hello, "; String str2 = "world!"; String result = str1 + str2; // Using + // or String result = str1.concat(str2); // Using concat method

2. Substring Extraction:

Extracting a portion of string using the ‘substring’ method.

String originalStr = "Hello, world!"; String subStr = originalStr.substring(0, 5); // Extracts "Hello"

3. String Length:

Finding the length(number of characters) of a string using the ‘length’ method.

String myStr = "Hello, world!"; int length = myStr.length(); // Length is 13

4. String Splitting:

Splitting a string into a array of substrings based on a delimiter using the ‘split’ method .

String myStr = "apple,banana,cherry"; String[] parts = myStr.split(","); // Splits into ["apple", "banana", "cherry"]

5. Find and Replace:

Finding and replacing the substrings within a string using the ‘replace’ method.

String myStr = "Hello, world!"; String newStr = myStr.replace("world", "universe"); // Replaces "world" with "universe"

6. Case Conversation:

Changing the characters within a string using the ‘toUppeCase’ and ‘toLowerCase’ methods.

String myStr = "Hello, World!"; String upperStr = myStr.toUpperCase(); // Converts to uppercase String lowerStr = myStr.toLowerCase(); // Converts to lowercase

7. String Trimming:

Removing leading and tailing whitespace characters from a string using the ‘trim’ method.

String myStr = " Hello, world! "; String trimmedStr = myStr.trim(); // Removes leading/trailing spaces

8. Formatting:

Formatting strings using the ‘String.format’ method and format specifiers.

String name = "Alice"; int age = 30; String formattedStr = String.format("Name: %s and Age: %d", name, age); // Formats the string System.out.println(formattedStr); //Name: Alice and Age: 30

9. String Builder & String Buffer:

For efficient string concatenation and manipulation of large strings, you can use ‘StringBuilder’ (non-thread- safe) or ‘StringBuffer’ (thread-safe).

StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(", "); sb.append("world!"); String result = sb.toString(); // Converts StringBuilder to a String

StringBuffer str = new StringBuffer(“abc”); Str.concat(“d”); System.out.println(str); // Converts StringBuffer to a String

These are some of the fundamental string manipulation operations in Java. Java’s rich standard library provides a wide range of methods and classes for more advanced string handling, making it a versatile language for working with text data.

36 views0 comments



bottom of page