Reputation: 53
How can I construct a condition that if a phrase has the name "x", then "x" is ignored when the phrase is displayed?
Example:
if(item.contains("Text"))
{
//Then ignore "Text" and display the remaining mill
}
Upvotes: 4
Views: 1917
Reputation: 1045
here, replace() can be used. public String replace(char oldChar, char newChar)
Parameters:
oldChar : old character
newChar : new character
public class ReplaceExample1{
public static void main(String args[]){
String s1="stackoverflow is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}
}
O/P:
steckoverflow is e very good website
Upvotes: 4
Reputation: 324
Not the best way, but off the top of my head:
String x = "This is Text";
String[] words;
String newX = "";
words = x.split(" ");
for(int i = 0; i < words.length; i++) {
if(!words[i].equals("Text"))
newX = newX + " " + words[i];
}
System.out.println(newX);
Upvotes: 2
Reputation: 48258
You can use the indexOf() method combined with a ternary operator
String val = "How can I construct a condition that if a phrase ";
String valFinal = val.indexOf("that") != -1 ? val.replace("that", "") : val;
System.out.println(valFinal);
Upvotes: 3
Reputation: 59950
You can easily use :
String item = "This is just a Text";
if (item.contains("Text")) {
System.out.println(item.replace("Text", ""));
}
Upvotes: 6