Java从单词中删除部分

时间:2018-04-07 00:40:56

标签: java

您好,我无法完成这项工作,如果主要单词中包含该单词应删除,则会给出一个主要单词后跟另一个子单词。

//Example
//fmrog (in.nextLine)(main word)
//4  (in.nextInt)(the amount of sub words)
//roc(in.nextLine)(not contained)
//gor(in.nextLine)(not contained)
//rog(in.nextLine)(contained)
//ogr(in.nextLine)(not contained)
//result:fm
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    StringBuilder mainWord = new StringBuilder(in.nextLine);
    int n = in.nextInt();
    StringBuilder MainWord2 = new StringBuilder(mainWord);
    in.nextLine();
    for (int i = 0; i < n; i++) {
        String subWord = in.nextLine();
        int chars = subWord.length();
        if (chars> mainWord.length()){
            continue;
        }
        for (int j = 0; j < subWord.length(); j++) {
            int r = 0;

            for (int k = 0; k < mainWord.length(); k++) {
                r++;
                if (k > MainWord2.length() - 1) {
                    break;
                }
                if (MainWord2.charAt(k) == subWord.charAt(j)) {
                    break;
                }
            }
            if (r <= MainWord2.length() && MainWord2.charAt(r-1) == subWord.charAt(j)) {
                MainWord2.deleteCharAt(r - 1);
                if (j >= subWord.length() -1 ) {
                    mainWord = MainWord2;
                    break;
                }
            }
            if (r > MainWord2.length()) {
                MainWord2 = mainWord;
                break;
            }

        }
    }
        System.out.println(mainWord);
    }
}

老实说,我被困了,也许有一种更简单的方法可以解决这个问题。最重要的是,当我写一个案例如:&#34; super 2 pe surr&#34;最后在&#34; surr&#34;当我删除chatAt时,两个StringBuilders开始作为一个,其中一个也发生了变化

2 个答案:

答案 0 :(得分:1)

无需让它如此复杂。

String input = // complete user input
String[] words = String.split(input);
String mainWord = words[0];
int numWords = Integer.parseInt(words[1]); // this variable isn't needed

for(int i = 2; i < words.length; i++) {
  if (mainWord contains words[i]) {
    mainWord = mainWord.replace(words[i], ""); // remove subword from mainword
  }
}

最后,mainWord将是原始的mainWord,没有后来输入的任何子词。

答案 1 :(得分:0)

   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    in.nextLine();
    String[] words = new String[n];
    for (int i = 0; i <n ; i++) {
        words[i] = in.nextLine();
    }
   String mainWord = words[0];
    for (int i = 1; i <words.length ; i++) {
        if (mainWord.contains(words[i])){
            mainWord = mainWord.replace(words[i], "");
        }
    }
    System.out.println(mainWord);
   }
   }

这里的问题是,如果字母不是彼此相邻的字母,则不会删除子字。