How to remove a particular character from a string ?

1- Using Recursion we can easily remove character from String

class RemoveCharacter{


public static void main(String []args){


String response = xRemoving("ddxxbbxxccxx") ;

System.out.println(response);


}


private static String  xRemoving(String str){

// we are creating base case, if string is empty function return empty String


if(str.length()==0){

return str ;

}


String newString = "";


// we are checking String Character from 0 index to length-1,if deleting character find we not adding that index character and move to another character and  doing same things again and again using recursion



if(str.charAt(0)!= 'x'){

newString =  newString + str.charAt(0);

}


String smallAns = xRemoving(str.substring(1));


return newString + smallAns;


}



}

2 - Using Loop  remove a particular character from a string ? 

class RemovingCharacter {

public static void main(String [] args){

String str =  removingElement("rbbbrrrcccdddrrr");

System.out.println(str);


}

/// creating function for deleting element'

public static String removingElement(String str){

String newString = "";

for(int i=0;i<str.length();i++){

if(str.charAt(i)!= 'r'){

newString = newString + str.charAt(i);

}



}

return newString ;

}

}

Rajeshbhatt12

My name is Rajesh Bhatt. I am working as a senior android developer . I have created this blog for kotlin ,java and Android Development interview questions etc..

Previous Post Next Post