1
votes

trouver le mot suivant d'un mot dans une chaîne

J'ai écrit le code suivant pour obtenir le mot suivant d'une chaîne en Java. Je pense que c'est très brut et je ne devrais pas avoir à écrire autant de code pour cela, mais je n'ai pas trouvé d'autre moyen. Vous voulez savoir s'il existe de meilleures façons de faire de même:

am
very
null
life
null
null

Remarque: le mot d'entrée peut être n'importe quoi (plusieurs mots, un seul mot, un mot qui n'est pas dans une chaîne, etc.). P >

Test:

    String text = "I am very happy with life";

    System.out.println(StringUtil.getNextWord(text, "I"));
    System.out.println(StringUtil.getNextWord(text, "I am"));
    System.out.println(StringUtil.getNextWord(text, "life"));
    System.out.println(StringUtil.getNextWord(text, "with"));
    System.out.println(StringUtil.getNextWord(text, "fdasfasf"));
    System.out.println(StringUtil.getNextWord(text, text));

Sortie:

public static String getNextWord(String str, String word) {
    String nextWord = null;
    // to remove multi spaces with single space
    str = str.trim().replaceAll(" +", " ");
    int totalLength = str.length();
    int wordStartIndex = str.indexOf(word);
    if (wordStartIndex != -1) {
        int startPos = wordStartIndex + word.length() + 1;
        if (startPos < totalLength) {
            int nextSpaceIndex = str.substring(startPos).indexOf(" ");
            int endPos = 0;
            if (nextSpaceIndex == -1) {
                // we've reached end of string, no more space left
                endPos = totalLength;
            } else {
                endPos = startPos + nextSpaceIndex;
            }
            nextWord = str.substring(startPos, endPos);
        }
    }
    return nextWord;
}


0 commentaires

6 Réponses :


0
votes

Vous pouvez créer un tableau de mots en faisant ceci:

nextword = words[words.indexOf(word) + 1];

Cela divise la chaîne en chaînes lorsqu'elle est séparée par un espace. Notez que vous devez toujours couper la chaîne comme vous le souhaitez. Maintenant, vous pouvez en quelque sorte rechercher dans le tableau en trouvant un mot et en ajoutant 1 à l'index pour obtenir le suivant.

String[] words = str.split(" ");


3 commentaires

en fait, j'ai pensé à cette solution mais cela ne fonctionnerait pas si le mot d'entrée est composé de plusieurs mots.


puis divisez également les multi-mots et ajoutez la longueur à l'index


@Carlos López Marí words.indexOf (word) + 1 words est un tableau et non une chaîne. afin que vous puissiez appeler indexOf ()



0
votes

J'espère que c'est ce que vous recherchez:

very
life
with
am
There is no next string

Le résultat pour ce qui précède est:

public static void main(String[] args) {
    String text = "I am very happy with life";
    System.out.println(getNextWord(text,"am"));
    System.out.println(getNextWord(text,"with"));
    System.out.println(getNextWord(text,"happy"));
    System.out.println(getNextWord(text,"I"));
    System.out.println(getNextWord(text,"life"));
}
public static String getNextWord(String text,String finditsNext){
    String result = "There is no next string";
    try {
        int findIndex = text.indexOf(finditsNext);
        String tep = text.substring(findIndex);
        if(tep.indexOf(" ") >0) {
        tep = tep.substring(tep.indexOf(" ") + 1);
        if(tep.indexOf(" ") >0)
            result = tep.substring(0, tep.indexOf(" "));
        else
            result = tep;
        }
    }catch (IndexOutOfBoundsException ex){

    }
    return result;
}


0 commentaires

2
votes

Cela ressemble à un travail pour les regex. Quelque chose comme ceci:

public static String getNextWord(String str, String word){
    Pattern p = Pattern.compile(word+"\\W+(\\w+)");
    Matcher m = p.matcher(str);       
    return  m.find()? m.group(1):null;      
} 


2 commentaires

Bien. Pattern.quote (word) au lieu de word protégerait contre les mots contenant des caractères (non-word) comme un point ou un point d'interrogation.


Comment comparer les performances si je dois l'exécuter plusieurs fois? Fondamentalement, mon exigence complète est de trouver le prochain mot «droit» après le mot d'entrée donné du texte. Il se peut donc que je doive continuer à obtenir le mot suivant jusqu'à ce que je trouve le mot «juste».



0
votes

J'espère que cela servira votre objectif.

next word: End 

Entrée (un seul mot):

String str = "Auto generated method stub";
String word = "stub";

Sortie:

XXX

Entrée (multi-mots):

next word: Not Found 

Sortie:

String str = "Auto generated method stub";
String word = "was";

Entrée (mot manquant):

next word: method 

Sortie:

String str = "Auto generated method stub";
String word = "Auto generated";

Entrée (mot de fin):

XXX

Sortie:

next word: stub


0 commentaires

1
votes

Je pense que cette solution fonctionne correctement:

public static String getNextWord(String str, String word) {
    String[] strArr = str.split(word);
    if(strArr.length > 1) {
        strArr = strArr[1].trim().split(" ");
        return strArr[0];
    }
    return null;
}


0 commentaires

0
votes

Vous pouvez essayer le code ci-dessous.

public static String getNextWord(String str, String word) {
    try {
        List<String> text = Arrays.asList(str.split(" "));
        List<String> list = Arrays.asList(word.split(" "));
        int index_of = text.indexOf(list.get(list.size() - 1));
        return (index_of == -1) ? null : text.get(index_of + 1);
    } catch(Exception e) {
        return null;
    }
}


0 commentaires