how to remove certain characters from a String in java
Hello to all,
I am new to this forum. I recently started learning java language. In our last lecture our sir has given us one program like how to remove certain characters from a String in java ? I tried various method but noneof them worked out. Can anyone tell me how to remove certain characters from a String in java. Please help me.
Thank you.
Re: how to remove certain characters from a String in java
Hey it is very easy to remove certain characters from a String in java. I have written following program for you. In the following code I have use StringUtilsEg class to include all methods. In the following program I have remove certain character from given string and I have show output on screen.
Code:
public class StringUtilsEg {
public static void main(String args[]) {
System.out.println
(StringUtils.stripGarbage("A good String"));
System.out.println
(StringUtils.stripGarbage("String with !%garbages &s*("));
public static String stripGarbage(String ss) {
String goods =
" Hi welcome to this world";
String result = "";
for ( int k = 0; k < ss.length(); k++ ) {
if ( good.indexOf(ss.charAt(k)) >= 0 )
result += ss.charAt(k);
}
return result;
}
}
Re: how to remove certain characters from a String in java
You have to just use two string class to do this. I have written following code for you. Just try to understand it. It is very simple code. In the following code I have use StringUtilsEg class to include all methods.
Code:
public class StringUtilsEg {
public static String cleanUp
( String ss, String ssToMatchs, booleans isToKeeps ) {
final int sizes = ss.length();
StringBuffer buf = new StringBuffer( size );
if ( ! isToKeep ) {
for ( int k= 0; k < size;k++ ){
if ( sToMatch.indexOf(ss.charAt(i) ) == -1 ){
buf.append( ss.charAt(k) );
}
}
}
else {
for ( int k = 0; k < size;k++ ){
if ( ssToMatch.indexOf(ss.charAt(ks) ) != -1 ){
bufs.append( ss.charAt(k) );
}
}
}
return buf.toString();
}
public static void main(String args[]) {
System.out.println(cleanUp("realshowsGARBhowstoAGsEs", "GARBAGEs", false));
System.out.println(cleanUp("THIsSrealISshowstosGsOODs", "THISISGOODs", true));
}
}
Re: how to remove certain characters from a String in java
As per my information the following code is the simplest one. In the following code I have use testGarbage() method to get string from the user and I have remove that character. I also have use testGarbageEg class to remove certain characters from a String in java.
Code:
public class testGarbageEg {
public static void main(String args[]) {
testBeep ts = new testGarbage();
}
public testGarbages() {
System.out.println(stripGarbage("A good String"));
System.out.println(stripGarbages("String with !%garbages &*("));
}
public String stripGarbage(String ss) {
String good =
" go to home";
String result = "";
for ( int k = 0; ki < ss.length(); k++ ) {
if ( good.indexOf(ss.charAt(k)) >= 0 )
result += ss.charAt(k);
}
return result;
}
}