Best Way To Remove Single Character From String

Well, in the following example let us learn best way to remove single character from string.

While designing software using java we often come across a phase where we need to an extra bit of work.

Example: Best Way To Remove Single Character From String

Here in this example I have created a separate method remove_Character with two parameters namely str_Remove and position.

Also Read – 3 Best Ways In Java String Concatenation

public class Remove_String_Char {

public static void main(String[] args) {
 
String str_Given = "Core Java";
System.out.println("Before removing string character - " + str_Given);
System.out.println("After removing string character - " + remove_Character(str_Given, 3));

}
 
public static String remove_Character(String str_Remove, int position){
 
return str_Remove.substring(0,position) + str_Remove.substring(position + 1);
 
}

}

Output:

Best Way To Remove Single Character From String


using replaceall function

public class RemoveString
{
public static void main(String[] args)
{
String strExample = "George hates samantha"; System.out.println("Before : " + strExample);
strExample = strExample.replaceAll("hates", "loves"); System.out.println("After : " + strExample);
}
}

Output:

Before : George hates samantha
After : George loves samantha

remove only letters

In this example I have a string with numeric values and alphabet values. What if we wanted to remove all the letters from the given string.

public class RemoveString
{
public static void main(String[] args)
{
String strExample = "jd15352kLJJD55185716kdkLJJJ"; System.out.println("Before : " + strExample);
strExample = strExample.replaceAll("[a-zA-Z]", ""); System.out.println("After : " + strExample);
}
}

Output:

Before : jd15352kLJJD55185716kdkLJJJ
After : 1535255185716

Now all we have is just the numbers. If you want to see the space between letters. Just give space between double quotes like this,

strExample = strExample.replaceAll("[a-zA-Z]", " ");

And the output will be like this,

Before : jd15352kLJJD55185716kdkLJJJ
After :    15352     55185716

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *