【问题标题】:How to use 'if' to condition and ignore a word in a particular sentence?如何使用“if”来条件和忽略特定句子中的单词?
【发布时间】:2017-09-25 16:10:47
【问题描述】:

如何构造一个条件,如果短语的名称为“x”,那么在显示该短语时会忽略“x”?

示例:

if(item.contains("Text"))
{
    //Then ignore "Text" and display the remaining mill
}

【问题讨论】:

  • 您可以使用substring() 方法来获取忽略文本前后的String
  • 什么是“剩余工厂”?例子?

标签: java string if-statement


【解决方案1】:

您可以轻松使用:

String item = "This is just a Text";
if (item.contains("Text")) {
    System.out.println(item.replace("Text", ""));
}

【讨论】:

  • 为什么要先打扰contains?只需:String item = "This is just a Text"; System.out.println(item.replace("Text", "")); 如果不包含目标,replace 返回相同的字符串。编辑:如何在评论中创建代码块?
  • 是的@jingx 这是一个很好的观点,但也许 OP 需要一些操作而不仅仅是打印字符串,所以他/她应该使用 if,对吧?
【解决方案2】:

这里, 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

【讨论】:

    【解决方案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);
    

    【讨论】:

      【解决方案4】:

      不是最好的方法,但我想不到:

          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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-03
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        • 2020-01-28
        • 1970-01-01
        • 2021-12-19
        相关资源
        最近更新 更多