删除字符串中的单词(RemoveString)

时间:2017-01-27 20:10:17

标签: java string

所以基本上我需要帮助我需要帮助的是从一个刺痛中删除一个单词。我不知道如何使用数组,char等只是为了那些引用我的人。

Output Ex: 
Enter a sentence: I really like Jolly Ranchers.

Enter a string: really

I like Jolly Ranchers.

我只需要从句子中删除字符串中每次出现的字符串。提前感谢您的帮助!

(不寻找讲义,也许是伪代码或其他例子。)

5 个答案:

答案 0 :(得分:0)

你可以这样:

public static String remove(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence :");
        String sentence = sc .nextLine();
        System.out.println("Enter a word :");
        String word = sc .nextLine();
        String res ="";
        for(String words : sentence.split(" ")){
            if(!words.equalsIgnoreCase(word)){    //or words!=word if you want to NOT ignore the case
                res+=words+" ";
            }
        }
        return res;
    }   

public static void main(String[] args) {
    System.out.println(remove());
}

它看起来每个单词,只保留那些与你输入的单词不相等的单词

或者更短的方式:

public static String remove(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence :");
        String sentence = sc .nextLine();
        System.out.println("Enter a word :");
        String word = sc .nextLine();
        return sentence.replaceAll(word,"");
    } 

答案 1 :(得分:0)

使用replaceAll函数, 这个函数有两个参数

  1. 正则表达式 - 您要替换的字符串

  2. substr-要替换它的字符串 例如:

    newString = str1.replaceAll(regex, substr);

  3. newString是已编辑的字符串

    str1是您要编辑的字符串

答案 2 :(得分:0)

String.replaceAll适用于

package se.samples;

import java.util.Scanner;

public class WordRemover {
    static final String welcomeMessage = "Enter a sentence: ", 
            secondMessage = "Enter a string: ", 
            resultMessage = "";

    static String replace(String source, String that){
        return source.replaceAll(that, "");
    }

    public static void main(String[] args) throws Exception {
        System.out.print(welcomeMessage);
        try(Scanner s = new Scanner(System.in)){
            String input = s.nextLine();
            System.out.print(secondMessage);
            System.out.println(resultMessage + replace(input, s.nextLine()));
        }
    }

}

答案 3 :(得分:-1)

请试试这个

 String[] s = originalString.split(" ");
    String wordToRemove = StandardInput;
    String finalString ="";
    for(String word : s){
    if(!word.equals(wordToRemove )){
    System.out.Print(word);
    finalString += word+" ";
          }
    }

答案 4 :(得分:-2)

我相信字符串有替换方法,所以尝试类似str.replace("真的","")或者如果有多个则替换每个。我建议查看Java API以获得更多功能。