Манипулировать строк - PullRequest
       1

Манипулировать строк

1 голос
/ 10 января 2011

Я пытаюсь найти наиболее повторяющееся слово в строке с помощью этого кода:

public class Word 
{
    private String toWord;
    private int Count;

    public Word(int count, String word){
        toWord = word;
        Count = count;
    }

    public static void main(String args[]){
        String str="my name is neo and my other name is also neo because I am neo";
        String []str1=str.split(" ");
        Word w1=new Word(0,str1[0]);
        LinkedList<Word> list = new LinkedList<Word>();
        list.add(w1);
        ListIterator itr = list.listIterator();
        for(int i=1;i<str1.length;i++){
            while(itr.hasNext()){
                if(str1[i].equalsTO(????));
                else
                    list.add(new Word(0,str1[i]));
            }
        }
    }
}

Как сравнить строку из массива строк str1 со строкой, хранящейся в связанном спискеи затем, как мне увеличить соответствующее число.

Я тогда напечатаю строку с наибольшим количеством, я тоже не знаю, как это сделать.

Ответы [ 6 ]

4 голосов
/ 10 января 2011

Я бы предложил использовать HashMap вместо связанного списка.

Iterate through the string.<br> For each word,<br> Check if the word is in the Map,<br> If it is there increment count and<br> Otherwise insert with count 1

0 голосов
/ 10 января 2011

Используйте Apache Commons StringUtils org.apache.commons.lang.StringUtils , чтобы получить счет.

String str="my name is neo and my other name is also neo because I am neo";
// Make a unique list (java.util.Set) of words.
Set<String> stSet = new HashSet<String>(Arrays.asList(str.split(" ")));
int sz = stSet.size();
int[] counts = new int[sz];
Map<Integer,String> matches = new HashMap<Integer,String>(sz);
int i = 0;
for (String s : stSet) {
   // saves the individual word count in a sortable array.
   counts[i] = StringUtils.countMatches(str,s));
   // saves the word count and the word in a HashMap for easy retrieval.
   matches.put(counts[i],s);
   i++;
}
Arrays.sort(counts);
int max = counts.length - 1;
System.out.println("The the word with the most occurrances is: "+matches.get(counts[max])+", the number of occurrances is: "+counts[max]);
0 голосов
/ 10 января 2011

Я думаю, что вы можете использовать некоторые регулярные выражения здесь, как

    final String str = "my name is neo and my other name is also neo because I am neo";

    final String[] arr = str.split (" ");
    final Set <String> set = new HashSet <String> ();
    for (final String word : arr) {
        System.out.println ("arr " + word);
        set.add (word);
    }

    String preWord = "";
    int preCount = 0;
    for (final String word : set) {
        System.out.println ("----------------");

        final Pattern p2 = Pattern.compile ("\\b" + word + "\\b");
        final Matcher m2 = p2.matcher (str);
        int count = 0;

        while (m2.find ()) {
            count++;
        }

        System.out.println ("preCount " + preWord + ":" + word + ":" + preCount + ":" + count);

        if ((preCount < count)) {
            preWord = word;
            preCount = count;
            System.out.println ("assigning word " + word + ":" + count);
        }
    }

    System.out.println ("result " + preWord + ":" + preCount);
0 голосов
/ 10 января 2011

Использование Google Guava :

Multiset<String> words = HashMultiset.create(Splitter.on(" ").split(input));

Тогда

String topWord = words.isEmpty() ? null 
    : Iterables.get(Ordering.natural().immutableSortedCopy(words), 0);

Вы можете получить частоту верхнего слова с помощью words.count(topWord).

0 голосов
/ 10 января 2011

C #? Вы можете попробовать использовать LINQ GroupBy, а затем Count или Max - очень просто.

0 голосов
/ 10 января 2011

Вам нужно сохранить каждое слово в списке, возможно, длинный с переменной count, которая указывает, сколько раз использовалось это слово.

Для каждого слова увеличивайте счет, если оно уже естьсписок или добавьте его в список, если это не так.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...