繁体   English   中英

如何将Java中一个字符串的单词与另一个字符串的单词进行比较,并在匹配时将单词分开?

[英]How to compare words of one string in Java with words of another string and separate the words on match?

This was an interview question. You are told to take string input from user & output a string (or array of string) separated by spaces with meaningful words matching from another string called as Dictionary. You have a dictionary function to check if word exists or not.
For example:
if Input is "howareyou" Output should be "how are you".
where the words 'how', 'are', 'you' are exist in dictionary string.

One more example:
Input: "somethingneedstobedone Output: "something needs to be done (Assuming that dictionary has words like something, needs, to, be, done.

I am not getting when to do k++ if there is no match.

The code I tried:

public class Sample1 {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int i,j,k,len;
    String[] dict= {"how","are","you","something","needs","to","be","done"};
    //StringBuilder str=new StringBuilder("howareyou");
    StringBuilder str=new StringBuilder("somethingneedstobedone");
    len=str.length();
    for(i=0,j=0,k=0;i<len;i++)
    {
        for(j=i+1;j<len;j++)
        {
            if(dict[k].toString().equals(str.substring(i, j)))
            {
                str.insert(j, " ");
                k++;
            }
        }
    }
    System.out.println(str);
    sc.close();
}

The commented case works well, but help me to get second case worked.

您遇到的问题(以及第一个字符串成功而第二个字符串未成功的原因)与dict中的单词顺序有关。 您当前的实现检查dict中的单词是否完全按照输入dict的顺序出现在字符串中-找到第一个单词后,在空格中查找第二个单词。 如果找不到下一个单词,则不会继续该过程。

有很多方法可以重写代码以获得所需的内容,但是最小的更改是:

public class Sample1 {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
int i,j,k,len;
    String[] dict= {"how","are","you","something","needs","to","be","done"};
    //StringBuilder str=new StringBuilder("howareyou");
    StringBuilder str=new StringBuilder("somethingneedstobedone");
    len=str.length();
    for(i=0,j=0;i<len;i++) //removed k from here
    {
        for(j=i+1;j<len;j++)
        {
          for (k=0;k<dict.length;k++) { //added this loop!
            if(dict[k].toString().equals(str.substring(i, j)))
            {
                str.insert(j, " ");
            }
          } //Loop closing for k - the dictionary
        }
    }
    System.out.println(str); 
    sc.close();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM