English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

if you have two strings, and there is an instance of one string in the second string, how do you remove that string? for example, string 1 is, "that snowman rox" and string 2 is "snow", how do you remove "snow" from "that snowman rox?"

2006-11-01 15:27:18 · 2 answers · asked by ♥heartbroken♥ 3 in Computers & Internet Programming & Design

2 answers

You can use the following code for the same:-
/* ------------------------------------------------------------------ */
public class RemoveMatchingString
{
public String removeString(String mainString, String removeString)
{
String newString = mainString;
int removeStringLength = removeString.length();
int removeStringPosition = -1;
do
{
removeStringPosition = newString.lastIndexOf( removeString );
if(removeStringPosition>-1)
{
int currentLength = newString.length();
String tempString = newString.substring(0, removeStringPosition) + newString.substring( removeStringPosition + removeStringLength, currentLength);
newString = tempString;
}
}
while (removeStringPosition>-1);
return newString;
}

public static void main(String [] args)
{
RemoveMatchingString rMString = new RemoveMatchingString();
String mainString = "that snowman rox";
String removeString = "snow";
String newString = rMString.removeString( mainString, removeString);
System.out.println( "mainString: " + mainString );
System.out.println( "removeString: " + removeString);
System.out.println("newString: " + newString);
}
}
/* ------------------------------------------------------------------ */

2006-11-01 16:05:13 · answer #1 · answered by mashiur1973 2 · 0 0

String in = "that snowman rox";
String regex = "snow";//literal works, but beware of special regex chars
String out = in.replaceAll(regex, "");//replace matches with empty string

//result is out = "that man rox"

2006-11-02 16:09:58 · answer #2 · answered by vincentgl 5 · 0 0

fedest.com, questions and answers