String manipulation

String manipulation in Java involves various methods provided by the String class and other related classes (e.g., StringBuilder, StringBuffer). These methods allow you to perform operations such as concatenation, substring extraction, search, replace, case conversion, and more. if we give a dot(.) after the string variable there will be show a lot of method names.

As we have said before there are some methods in the String class that are very helpful to execute a Java program according to our requirements. Now we will discuss some of them.

Length Method:

In Java, the String class provides a method called length() to determine the length or number of characters in a string. The length of the sequence of characters represented by this object. The length() method returns an integer representing the number of characters in the string, including spaces, punctuation, and special characters.

It’s essential to use the length() method when you need to determine the size of a string dynamically or when performing operations that depend on the length of a string.

Example:
public static void main(String[] args) {
    
        String name;
    
        name = "maria";
    
        int lengthofcharacter = name.length();
    
        System.out.println("length of character is " + lengthofcharacter);
    
       }
    
}
Output:

length of character is 5

In this code, The string “maria” has five characters (‘m’, ‘a’, ‘r’, ‘i’, ‘a’), “int lengthofcharacter = name.length();”: This line declares a new variable lengthofcharacter of type int and assigns the result of the length() method to it. The length() method is called on the string name and returns the number of characters in the string. which is 5. The output statement then prints the message “length of character is” followed by the value 5, giving us “length of character is 5” as the final output.

Index Of Method:

There are two versions of the indexOf() method:

There are two versions of the indexOf() method:

indexOf(int ch): This version takes a single character (int type representing the Unicode value of the character) as an argument and returns the index of the first occurrence of that character in the string.

indexOf(String str): This version takes a string (String type) as an argument and returns the index of the first occurrence of that substring in the string.

If the character or substring is not found in the string, the indexOf() method returns -1.

It’s important to note that the indexOf() method searches for the first occurrence of the specified character or substring. If you need to find all occurrences or start searching from a specific index, you can use other methods like lastIndexOf() or utilize loops and additional logic

Example:
public class StringManupulation {

    public static void main(String[] args) {
        String name;
        name = "maria";
        int indexOfi = name.indexOf('r');
        System.out.println("index of char r is " + indexOfi);
    }

}
Output:

index of char r is 2

Explanation:

Let’s describe the program:

  • String name;: This line declares a variable named name of type String. It’s a reference to a string object, but it’s not yet assigned any value.
  • name = “maria”;:Here, the name variable is assigned the value “maria”. So now, the name variable points to the string object containing the characters “maria”.
  • int indexOf i = name.indexOf(‘r’);:The indexOf() method is used on the name string to find the index of the character ‘r’. This method returns the index (position) of the first occurrence of the specified character in the string. In this case, the character ‘r’ appears at index 2 (since indices are zero-based), so the value of indexOfi will be 2.
  • System.out.println(“index of char r is ” + indexOfi);:This line prints a message along with the value of the indexOfi variable. The + operator is used for string concatenation. The message “index of char r is ” is concatenated with the value of indexOfi, which is 2. The whole message is then printed to the console.

In summary, the code assigns the string “maria” to the variable name, finds the index of the character ‘r’ using the indexOf() method (which is 2), and then prints a message along with the index value to the console. The output will be: “index of char r is 2”.

CharAt() Method:

This method is a built-in method in the Java String class that allows you to retrieve a character at a specific index within a string. The index is zero-based, which means the first character of the string is at index 0, the second character is at index 1, and so on.

It’s important to note that if you try to access an index that is out of bounds (negative or greater than or equal to the length of the string), it will result in a StringIndexOutOfBoundsException. So, make sure to ensure the validity of the index before using the charAt() method

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String name;
        name = "maria";
        char i = name.charAt(4);
        System.out.println("4 no charter is of this String is " + i);
        }
}
Output:

4 no charter is of this String is a

Explanation:
  1. `String name;`: This line declares a variable named `name` of type `String`. It’s a reference to a string object, but it’s not yet assigned any value.
  2. `name = “maria”;`: Here, the `name` variable is assigned the value `”maria”`. So now, the `name` variable points to the string object containing the characters “maria”.
  3. `char i = name.charAt(4);`: This line retrieves the character at index 4 from the string stored in the `name` variable. In Java, string indices are zero-based, so index 4 corresponds to the fifth character in the string. In the case of `”maria”`, the fifth character is `’a’`. The retrieved character is assigned to the variable `i`.
  4. `System.out.println(“4 no charter is of this String is ” + i);`: This line prints a message along with the character retrieved from the string. The `+` operator is used for string concatenation. The message `”4 no charter is of this String is “` is concatenated with the character `i`, which is `’a’` in this case. The whole message is then printed to the console.

In summary, the code assigns the string `”maria”` to the variable `name`, retrieves the fifth character `’a’` from the string, and then prints a message along with that character using the `System.out.println()` method.

Concat() Method:

By using this method we can join two strings in Java. The concat() method in Java’s String class is used to concatenate two strings together. It takes a single argument, which is another string, and returns a new string that is the result of combining the caller string with the argument string.

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String name;
        name="maria";
        String newName = name.concat(" Alam");
        System.out.println("after concat " + newName);
        }
}
Output:

after concat maria Alam

Explanation:

Let me help you understand the code:

  1. `String name;`: This declares a variable named `name` of type `String` but doesn’t assign a value to it yet.
  2. `name = “maria”;`: Here, the value `”maria”` is assigned to the `name` variable. So, the `name` variable now holds the string “maria”.
  3. `String newName = name.concat(” Alam”);`: The `concat()` method is used to combine the string stored in the `name` variable (“maria”) with the string `” Alam”`. The result of this concatenation is assigned to a new variable named `newName`. So, `newName` now holds the string “maria Alam”.
  4. `System.out.println(“after concat ” + newName);`: This line prints a message along with the value stored in the `newName` variable. The `+` operator is used to concatenate the message “after concat ” with the value of `newName`, resulting in the output: “after concat maria Alam”.

In summary, the code creates a string variable `name` and assigns it the value “maria”. It then uses the `concat()` method to combine “maria” with ” Alam”, creating a new string stored in `newName`. Finally, it prints the concatenated string along with a message to the console.

SubString() Method:

The substring() method is a built-in method in Java’s String class that allows you to extract a portion of a string based on specified indices. This method returns a new string that represents the substring extracted from the original string.

To show the part of a specified string we use this method. This method Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

String variableName = variableName .substring(beginIndex);
String variableName = variableName .substring(beginIndex, endIndex);

It’s important to note that the endIndex parameter in the second form of the substring() method is exclusive. This means the character at the endIndex is not included in the extracted substring.

Also, if you don’t provide an endIndex, the substring() method will extract the substring from the beginIndex to the end of the string.

Keep in mind that the indices must be within the valid range of the string, otherwise, it will result in a StringIndexOutOfBoundsException

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String name;
        name = "maria";
        String a = name.substring(2);
        System.out.println("A part of name maria is: " + a);
        }
}
Output:

A part of name maria is: ria

Explanation:

Let’s describe the code:

  1. `String name;`: This line declares a variable named `name` of type `String`. It’s a reference to a string object, but it’s not yet assigned any value.
  2. `name = “maria”;`: Here, the `name` variable is assigned the value `”maria”`. So now, the `name` variable points to the string object containing the characters “maria”.
  3. `String a = name.substring(2);`: The `substring()` method is used on the `name` string to extract a substring starting from index 2 (inclusive). Index 2 corresponds to the third character, which is `’r’`. The extracted substring will include all characters from index 2 to the end of the string. This means that the value of `a` will be `”ria”`.
  4. `System.out.println(“A part of name maria is: ” + a);`: This line prints a message along with the value of the `a` variable. The `+` operator is used for string concatenation. The message `”A part of name maria is: “` is concatenated with the value of `a`, which is `”ria”`. The whole message is then printed to the console.

In summary, the code assigns the string `”maria”` to the variable `name`, extracts a substring starting from index 2 (inclusive) using the `substring()` method, and then prints a message along with the extracted substring `”ria”`. The output will be: “A part of name maria is: ria”.

StartsWith() Method:

To test if the string starts with the specified character or not we use Startwith() method. This method returns a boolean value (true or false) based on whether the original string begins with the specified prefix. This method can be useful in scenarios where you need to perform conditional checks based on the beginning of a string, such as checking for specific file extensions or validating user input.

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String name;
        name = "maria";
        boolean v = name.startsWith("i");
        System.out.println(v);
       }
}
Output:

false

Explanation:

Let’s explain the code:

  • String name;: We’re declaring a spot in memory where we can store text.
  • name = “maria”;: We’re filling that spot with the word “maria”.
  • boolean v = name.startsWith(“i”);:We’re checking if the word in that spot starts with the letter “i”. This gives us a “true” or “false” answer.
  • System.out.println(v);:We’re printing the answer we got in the previous step (whether the word starts with “i”) to the screen.

In summary, the code checks if the word “maria” starts with the letter “i”, and then it prints the result, which would be “false”, because “maria” doesn’t start with “i”

Replace() Method:

If we want to change a character of a string we use replace method. This method returns a string resulting from replacing all occurrences of oldChar in this string with newChar. The replace() method creates a new string with the replacements made and leaves the original string unchanged. If no occurrences of the character or substring to be replaced are found, the original string is returned as is.

Basic syntax of replace()method is:

String newString = originalString.replace(oldSubstring, newSubstring);

originalString: The original string in which you want to replace occurrences.

oldSubstring: The substring you want to replace.

newSubstring: The substring you want to replace oldSubstring with.

Example:
public class StManupulation_exm {
    public static void main(String[] args) {
        String name "Java,Python,c++,PHP";
        String v = name.replace(",","_");
        System.out.println(v);
     }
}
Output:

Java_Python_c++_PHP

Let’s go through the code step by step:

  1. `String name = “Java,Python,c++,PHP”;` : This line initializes a `String` variable named `name` with the value “Java,Python,c++,PHP”.
  2. `String v = name.replace(“,”, “_”);` : This line uses the `replace` method to replace all occurrences of the comma `,` in the `name` string with an underscore `_`. The result of this replacement is assigned to a new `String` variable named `v`.
  3. `System.out.println(v);`: This line prints the value of the `v` variable, which contains the modified string with replaced commas.

The `replace` method searches for all occurrences of the specified substring (in this case, just the comma `,`) and replaces them with the replacement string (in this case, an underscore `_`).

In the original string “Java,Python,c++,PHP”, all the commas have been replaced by underscores, resulting in the modified string “Java_Python_c++_PHP”.

CompareTo() Method:

This method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. If all the characters are the same then it returns 0. Otherwise, it returns the value on the basis of the Unicode value.

The result of this comparison is a number that tells you how the two words compare:

  • If the result is 0, it means the words are the same.
  • If the result is negative, your word comes before the other word.
  • If the result is positive, your word comes after the other word.

This method is case-sensitive. Syntax of compareTo() method is:

int compareTo(String anotherString)

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String name;
        name = "maria";                      // case         sensitive
        System.out.println("Result after Comparing the characters:"+name.compareTo("Maria"));
 
         }
}
Output:

Result after Comparing the characters: 32

Explanation:
  • The string stored in the name variable is “maria”.
  • The string “Maria” is the argument passed to the compareTo() method.
  • Since strings in Java are case-sensitive when using compareTo(), the lowercase “maria” is considered lexicographically greater than the uppercase “Maria”. This is because the Unicode value of lowercase characters is higher than that of uppercase characters. Therefore, “maria”.compareTo(“Maria”) would return a positive integer.. The printed output will show the Result after Comparing the characters: 32

If we want to ignore the case and upper case difference we can use compareToIgnoreCase method.

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String name;
        name = "maria";// ignore case
        System.out.println("Result after Comparing the characters: "+name.compareToIgnoreCase("Maria"));
     }
}
Output:

Result after Comparing the characters: 0

IsBlank() Method:

If we want to check if the string is blank or not we use IsBlank() method. It returns a Boolean value. It Returns true if the string is empty or contains only white space codepoints, otherwise, it returns false.

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String b = " ";
        boolean s = b.isBlank();
        System.out.println("The result is: "+s);
    }    
}
Output:

The result is: true

Explanation:

Here’s what each part does:

  • Declaring and Initializing a String Variable: This line creates a variable named b of type String and assigns it the value ” “. This means that variable b holds a single space character.
  • Checking if the String is Blank: The isBlank() method is called on the string stored in the variable b. This method is used to determine if a string contains only whitespace characters (spaces, tabs, line breaks) or is completely empty. In this case, the string ” ” (a single space) contains only whitespace, so s will be assigned the value true.
  • Printing the Result: The System.out.println() function is used to print the result to the console. Inside the parentheses, a message is provided along with the value of s. The message is “The result is: ” and then the value of s is concatenated to it.

So, if we put it all together: The variable b contains a single space character. The isBlank() method checks if b is blank, and it is, so s becomes true. The message “The result is: ” is combined with the value of s (true), and the entire message is printed to the console.

IsEmpty() Method:

This method is used to check if the String is empty or not. It returns true if, and only if, length() is 0. Otherwise, it returns false.

Example:
public class StringManupulation {
    public static void main(String[] args) {
        String b = " ";
        boolean  e = b.isEmpty();
        System.out.println("The result is: "+e);
     }
}
Output:

The result is: false

Explanation:

Let’s explain the code:

  • The variable b holds a single space character.
  • The isEmpty() method checks if b is empty. Since it contains a space, it’s not empty, and e becomes false.
  • The message “The result is: ” is combined with the value of e (false), and the entire message is printed to the console.

In simpler terms, this code checks whether the string stored in b is completely empty (no characters at all) and then displays the result as false because the string contains a space character.

Trim() Method:

In Java, the trim() method is used with strings to remove any leading (at the beginning) and trailing (at the end) whitespace characters, such as spaces, tabs, and line breaks. It doesn’t remove spaces or other characters within the string itself, only the whitespace characters at the beginning and end.

It’s important to keep in mind that the trim() method solely operates on the spaces or whitespace characters located at the start and end of a string. Any spaces or characters located within the string will not be eliminated.

 Example:
public class StManupulation_exm {
    public static void main(String[] args) {
        String address = "  256 Irving,Dallas,Texas";
        System.out.println("before trim:-" + address);
        System.out.println("after trim:-" + address.trim());
    }
}
Output:

before trim:- 256 Irving,Dallas,Texas

after trim:-256 Irving,Dallas,Texas

Explanation:

Let us concentrate on the code.

The `trim()` method is used to clean up a string by removing any extra spaces or whitespace characters at the beginning and end. It’s like tidying up a sentence by erasing spaces that don’t add any meaning.

In this code, You have an address with extra spaces at the beginning: `” 256 Irving,Dallas,Texas”`. The `trim()` method comes to the rescue and removes those leading spaces. It doesn’t touch the spaces within the address itself, just the ones that make the address look messy.

So, when you print the address before trimming, it’s like showing how messy it is:

before trim:-  256 Irving,Dallas,Texas

But when you print the address after trimming, it’s like presenting the cleaned-up version:

after trim:-256 Irving,Dallas,Texas

In essence, `trim()` helps you clean up strings by getting rid of unnecessary spaces, making them look neat and tidy.

Visited 1 times, 1 visit(s) today

Comments are closed.

Close