如何构造一个条件,如果短语的名称为“x”,则在显示短语时会忽略“x”?
示例:
if(item.contains("Text"))
{
//Then ignore "Text" and display the remaining mill
}
答案 0 :(得分:6)
您可以轻松使用:
String item = "This is just a Text";
if (item.contains("Text")) {
System.out.println(item.replace("Text", ""));
}
答案 1 :(得分:4)
这里, 可以使用 replace()。 public String replace(char oldChar,char newChar)
<强>参数:强>
oldChar :旧字符
newChar :新角色
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
答案 2 :(得分:3)
您可以将 indexOf() 方法与三元运算符结合使用
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);
答案 3 :(得分:2)
不是最好的方式,但不是我的头脑:
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);