top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

how to remove extra character in the string using java?

To remove extra characters from a string in Java, you can use various methods depending on the specific requirements. Here are some examples:

  1. Removing all whitespace characters (spaces, tabs, newlines) from a string:

String input = " Hello \t World\n ";

String output = input.replaceAll("\\s+", "");

System.out.println(output); // Output: "HelloWorld"


2. Removing specific characters from a string using replace() method:


String input = "Hello World!!!";

String output = input.replace("!", "");

System.out.println(output); // Output: "Hello World"


3.Removing characters from the beginning and/or end of a string using trim() method:


String input = " Hello World ";

String output = input.trim();

System.out.println(output); // Output: "Hello World"


4.Removing characters at a specific position in a string using substring() method:

String input = "Hello World!!!";

String output = input.substring(0, 11) + input.substring(14);

System.out.println(output); // Output: "Hello World"


5.To remove characters from a Java string using the substring() method, you can concatenate the parts of the original string that you want to keep. Here's an example:


String originalString = "Hello World!";

String characterToRemove = "o";

int indexToRemove = originalString.indexOf(characterToRemove);


if (indexToRemove >= 0) {

String stringWithoutCharacter = originalString.substring(0, indexToRemove) + originalString.substring(indexToRemove + 1);

System.out.println(stringWithoutCharacter); // Output: "Hell World!"

} else {

System.out.println(originalString);

}


In this example, we first find the index of the character we want to remove using the indexOf() method. If the character is found in the string (indexToRemove >= 0), we concatenate the substring before the index and the substring after the index to get the new string without the character. If the character is not found in the string, we simply print the original string.


Thank you All

Keep Learning !!!


136 views0 comments

Recent Posts

See All

Kommentare

Mit 0 von 5 Sternen bewertet.
Noch keine Ratings

Rating hinzufügen
bottom of page