String Modifying Methods in Java

Introduction

Java provides several methods to modify strings. These methods allow you to create new strings by modifying the content of existing strings, which are immutable in Java. This tutorial will cover various string-modifying methods with examples.

Table of Contents

  1. substring()
  2. concat()
  3. replace()
  4. replaceAll()
  5. replaceFirst()
  6. toUpperCase()
  7. toLowerCase()
  8. trim()
  9. split()
  10. Complete Example Program
  11. Conclusion

1. substring()

The substring() method returns a new string that is a substring of the original string. It takes one or two arguments: the start index and optionally the end index.

Syntax:

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

Example:

public class SubstringExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String substr1 = str.substring(7);
        String substr2 = str.substring(0, 5);

        System.out.println("Substring from index 7: " + substr1);
        System.out.println("Substring from index 0 to 5: " + substr2);
    }
}

Output:

Substring from index 7: World!
Substring from index 0 to 5: Hello

2. concat()

The concat() method concatenates the specified string to the end of the original string.

Syntax:

public String concat(String str)

Example:

public class ConcatExample {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";
        String result = str1.concat(", ").concat(str2).concat("!");

        System.out.println("Concatenated string: " + result);
    }
}

Output:

Concatenated string: Hello, World!

3. replace()

The replace() method replaces all occurrences of a specified character or substring with a new character or substring.

Syntax:

public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)

Example:

public class ReplaceExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String result1 = str.replace('o', '0');
        String result2 = str.replace("World", "Java");

        System.out.println("Replaced 'o' with '0': " + result1);
        System.out.println("Replaced 'World' with 'Java': " + result2);
    }
}

Output:

Replaced 'o' with '0': Hell0, W0rld!
Replaced 'World' with 'Java': Hello, Java!

4. replaceAll()

The replaceAll() method replaces each substring that matches the given regular expression with the given replacement.

Syntax:

public String replaceAll(String regex, String replacement)

Example:

public class ReplaceAllExample {
    public static void main(String[] args) {
        String str = "Hello123World";
        String result = str.replaceAll("[0-9]", "#");

        System.out.println("Replaced all digits with '#': " + result);
    }
}

Output:

Replaced all digits with '#': Hello###World

5. replaceFirst()

The replaceFirst() method replaces the first substring that matches the given regular expression with the given replacement.

Syntax:

public String replaceFirst(String regex, String replacement)

Example:

public class ReplaceFirstExample {
    public static void main(String[] args) {
        String str = "Hello123World123";
        String result = str.replaceFirst("[0-9]", "#");

        System.out.println("Replaced first digit with '#': " + result);
    }
}

Output:

Replaced first digit with '#': Hello#23World123

6. toUpperCase()

The toUpperCase() method converts all characters in the string to uppercase.

Syntax:

public String toUpperCase()

Example:

public class ToUpperCaseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String result = str.toUpperCase();

        System.out.println("Uppercase string: " + result);
    }
}

Output:

Uppercase string: HELLO, WORLD!

7. toLowerCase()

The toLowerCase() method converts all characters in the string to lowercase.

Syntax:

public String toLowerCase()

Example:

public class ToLowerCaseExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String result = str.toLowerCase();

        System.out.println("Lowercase string: " + result);
    }
}

Output:

Lowercase string: hello, world!

8. trim()

The trim() method removes whitespace from both ends of the string.

Syntax:

public String trim()

Example:

public class TrimExample {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";
        String result = str.trim();

        System.out.println("Trimmed string: '" + result + "'");
    }
}

Output:

Trimmed string: 'Hello, World!'

9. split()

The split() method splits the string into an array of substrings based on the specified delimiter.

Syntax:

public String[] split(String regex)
public String[] split(String regex, int limit)

Example:

import java.util.Arrays;

public class SplitExample {
    public static void main(String[] args) {
        String str = "apple,banana,cherry";
        String[] result = str.split(",");

        System.out.println("Split string: " + Arrays.toString(result));
    }
}

Output:

Split string: [apple, banana, cherry]

10. Complete Example Program

Here is a complete program that demonstrates the various string modifying methods discussed above.

Example Code:

import java.util.Arrays;

public class StringModifyingMethods {
    public static void main(String[] args) {
        String str = "   Hello, World!   ";

        // substring() method
        String substr1 = str.substring(7);
        String substr2 = str.substring(1, 5);
        System.out.println("Substring from index 7: '" + substr1 + "'");
        System.out.println("Substring from index 1 to 5: '" + substr2 + "'");

        // concat() method
        String str1 = "Hello";
        String str2 = "World";
        String result = str1.concat(", ").concat(str2).concat("!");
        System.out.println("Concatenated string: " + result);

        // replace() method
        String result1 = str.replace('o', '0');
        String result2 = str.replace("World", "Java");
        System.out.println("Replaced 'o' with '0': " + result1);
        System.out.println("Replaced 'World' with 'Java': " + result2);

        // replaceAll() method
        String str3 = "Hello123World";
        String result3 = str3.replaceAll("[0-9]", "#");
        System.out.println("Replaced all digits with '#': " + result3);

        // replaceFirst() method
        String str4 = "Hello123World123";
        String result4 = str4.replaceFirst("[0-9]", "#");
        System.out.println("Replaced first digit with '#': " + result4);

        // toUpperCase() method
        String upperCaseResult = str.toUpperCase();
        System.out.println("Uppercase string: " + upperCaseResult);

        // toLowerCase() method
        String lowerCaseResult = str.toLowerCase();
        System.out.println("Lowercase string: " + lowerCaseResult);

        // trim() method
        String trimmedResult = str.trim();
        System.out.println("Trimmed string: '" + trimmedResult + "'");

        // split() method
        String str5 = "apple,banana,cherry";
        String[] result5 = str5.split(",");
        System.out.println("Split string: " + Arrays.toString(result5));
    }
}

Output:

Substring from index 7: ' World!   '
Substring from index 1 to 5: ' Hel'
Concatenated string: Hello, World!
Replaced 'o' with '0':    Hell0, W0rld!
Replaced 'World' with 'Java':    Hello, Java!
Replaced all digits with '#': Hello###World
Replaced first digit with '#': Hello#23World123
Uppercase string:    HELLO, WORLD!
Lowercase string:    hello, world!
Trimmed string: 'Hello, World!'
Split string: [apple, banana, cherry]

11. Conclusion

Java provides several methods to modify strings, each serving different purposes and use cases.

The substring(), concat(), replace(), replaceAll(), replaceFirst(), toUpperCase(), toLowerCase(), trim(), and split() methods offer a wide range of functionality for string manipulation. Understanding these methods will help you manipulate and analyze strings more effectively in Java.

Comments