Java 返回下N个单词的有效方法&;要显示的前N个单词

Java 返回下N个单词的有效方法&;要显示的前N个单词,java,android,Java,Android,我希望允许用户一次查看一个字符串,N个单词。它们可以向前和向后移动,这样向后将显示前面的N个单词。另外,由于我们受屏幕空间的限制,所以我只想选择适合的单词,最多n个(完整单词,否…) 因此,我创建了初始的不太漂亮的方法: import java.util.ArrayList; public class Test { static String text = "This is a dummny sentence. I am a dummy sentence two. This is d

我希望允许用户一次查看一个字符串,N个单词。它们可以向前和向后移动,这样向后将显示前面的N个单词。另外,由于我们受屏幕空间的限制,所以我只想选择适合的单词,最多n个(完整单词,否…)

因此,我创建了初始的不太漂亮的方法:

import java.util.ArrayList;

public class Test {

    static String text = "This is a dummny sentence. I am a dummy sentence two. This is dummy sentence 3. This is a dummy sentence";

    static int currentWordIndex = 0;

    public static void main(String[] args) {

        String nextWords = getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords);
        System.out.println("Index: " + currentWordIndex);

        nextWords = getNextWords(3, 30);
        System.out.println("Sentence: " + nextWords);
        System.out.println("Index: " + currentWordIndex);

        nextWords = getNextWords(3, 30);
        System.out.println("Sentence: " + nextWords);
        System.out.println("Index: " + currentWordIndex);

        nextWords = getNextWords(3, 30);
        System.out.println("Sentence: " + nextWords);
        System.out.println("Index: " + currentWordIndex);


        String prevWords = getPreviousWords(3, 30);
        System.out.println("Previous Sentence: " + prevWords);
        System.out.println("Index: " + currentWordIndex);

        prevWords = getPreviousWords(3, 30);
        System.out.println("PreviousSentence: " + prevWords);
        System.out.println("Index: " + currentWordIndex);

        prevWords = getPreviousWords(3, 30);
        System.out.println("PreviousSentence: " + prevWords);
        System.out.println("Index: " + currentWordIndex);

        nextWords = getNextWords(3, 30);
        System.out.println("Sentence: " + nextWords);
        System.out.println("Index: " + currentWordIndex);

        nextWords = getNextWords(3, 30);
        System.out.println("Sentence: " + nextWords);
        System.out.println("Index: " + currentWordIndex);


    }

    public static String getPreviousWords(int n, int maxCharacterLength) {
        ArrayList<String> initialSelection = new ArrayList();
        String[] splitWords = text.split(" ");
        int charCount = 0;
        int maxN = currentWordIndex - n;
        if(maxN < 0) {
            maxN = 0;
        }
        for (int i = maxN; i < currentWordIndex; i++) {
            if(i > splitWords.length) {
                break;
            }
            initialSelection.add(splitWords[i]);
            charCount += splitWords[i].length();
        }

        if (charCount > maxCharacterLength) {
            charCount = 0;
            for (int x = 0; x < initialSelection.size(); x++) {
                if (initialSelection.size() == 0)
                    return null;
                initialSelection.remove(initialSelection.size() - 1);
                for (String s : initialSelection) {
                    charCount += s.length();
                }
                if (charCount <= maxCharacterLength) {
                    break;
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String s : initialSelection) {
            sb.append(s + " ");
        }
        if(currentWordIndex - initialSelection.size() < 0) {
            currentWordIndex = 0;
        } else {
            currentWordIndex -= initialSelection.size();
        }
        return sb.toString().substring(0, sb.length());
    }

    /**
     * Obtains the next n number of words given the maximum number of characters that can fit on the screen.
     * If not all words fit on the screen
     *
     * @param n                  number of words
     * @param maxCharacterLength of text that can fit on the screen.
     * @return next words
     */
    public static String getNextWords(int n, int maxCharacterLength) {
        ArrayList<String> initialSelection = new ArrayList();
        int charCount = 0;
        String[] splitWords = text.split(" ");
        int maxN = currentWordIndex + n;
        if (maxN > splitWords.length - 1) {
            maxN = splitWords.length - 1;
        }
        // add the words
        for (int i = currentWordIndex; i < maxN; i++) {
            if (i > splitWords.length - 1)
                break;
            initialSelection.add(splitWords[i]);
            charCount += splitWords[i].length();
        }

        // if there's too many, remove the last word until everything fits
        if (charCount > maxCharacterLength) {
            charCount = 0;
            for (int x = 0; x < initialSelection.size(); x++) {
                if (initialSelection.size() == 0)
                    return null;
                initialSelection.remove(initialSelection.size() - 1);
                for (String s : initialSelection) {
                    charCount += s.length();
                }
                if (charCount <= maxCharacterLength) {
                    break;
                }
            }
        }

        // add back into a string
        StringBuilder sb = new StringBuilder();
        for (String s : initialSelection) {
            sb.append(s + " ");
        }

        // update the index/pivot based on the words selected
        if (currentWordIndex + initialSelection.size() < splitWords.length - 1) {
            currentWordIndex += initialSelection.size();
        } else {
            currentWordIndex = splitWords.length;
        }
        return sb.toString().substring(0, sb.length());
    }

}
这是不正确的。似乎下一个和上一个正在工作-只是在它们之间切换时不起作用。它应该说:

Next Sentence: One two three four five. 
Index: 5
Next Sentence: Six Seven Either, 
Index: 8
Next Sentence: Nine, Ten, Eleven. 
Index: 11
Next Sentence: Twelve thirdteen fourteen 
Index: 14
Previous Sentence: Nine, Ten, Eleven.
Index: 11
PreviousSentence: Six, Seven, Either. 
Index: 8
PreviousSentence: three four five, 
Index: 5
Next Sentence: Six Seven Either, 
Index: 8
Next Sentence: Nine, Ten, Eleven. 
Index: 11
我明白问题是什么:在getNext递增之后,它在下一句的开头设置标记。因此,当调用getPrevious时,它调用最后一句(当前已显示的一句)

所以我认为解决方案是同时有一个开始和结束标记——标记句子索引的开始和结束

但我想知道是否有人有更优雅的解决方案来解决这个问题

试试这个

 public class Test {

    static String text = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen";

    static int currentWordIndex = 0;
    private static List<String> list = new LinkedList<String>();

    public void createTokens() {
        String[] splitWords = text.split(" ");
        for (int i = 0; i < splitWords.length; i++) {
            list.add(splitWords[i]);
        }
    }

    public String getPreviousWords(int n, int maxCharacterLength) {
        StringBuilder strBuilder = new StringBuilder();
        int characterCount = 0;
        int item_size = 0;
        // you need to check this negative or not
        currentWordIndex = currentWordIndex - n; 
        ListIterator<String> nextIter = list.listIterator(currentWordIndex);
        while (nextIter.hasPrevious() && item_size < n) {
            String elem = (String) nextIter.previous();
            characterCount += elem.length();
            if (characterCount > maxCharacterLength) {
                break;
            }
            strBuilder.append(elem);
            strBuilder.append(" ");
            item_size++;
        }

        return strBuilder.toString();
    }

    /**
     * Obtains the next n number of words given the maximum number of characters
     * that can fit on the screen. If not all words fit on the screen
     *
     * @param n
     *            number of words
     * @param maxCharacterLength
     *            of text that can fit on the screen.
     * @return next words
     */
    public String getNextWords(int n, int maxCharacterLength) {
        StringBuilder strBuilder = new StringBuilder();
        int characterCount = 0;
        int item_size = 0;
        ListIterator<String> nextIter = list.listIterator(currentWordIndex);
        while (nextIter.hasNext() && item_size < n) {
            String elem = (String) nextIter.next();
            characterCount += elem.length();
            if (characterCount > maxCharacterLength) {
                break;
            }
            strBuilder.append(elem);
            strBuilder.append(" ");
            item_size++;
        }
        return strBuilder.toString();

    }

}
输出:

Sentence: one two three four five
Sentence: six seven eight nine ten 
Sentence: eleven twelve thirteen fourteen 
Sentence: ten nine eight seven six 

因为我想让它与@mithat konuk解决方案一起工作。但我认为使用子列表可能更好

public class Test2 {

    public static void main(String[] args) {
        Test2 t = new Test2();
        t.createTokens();
        String nextWords = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords);
        String nextWords2 = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords2);
        String nextWords3 = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords3);

        String previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);

        nextWords = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords);
    }


    static String text = "I am a cat who sat on a mat and yelled as someone who was fat";

    private static List<String> list = new LinkedList<String>();

    // index of the start of the next sentence (i.e also the end of the sentence that is currently being displayed)
    static int nextWordIndex = 0;
    // index of the first word of the current sentence being displayed.
    static int firstWordIndex = 0;

    public void createTokens() {
        String[] splitWords = text.split(" ");
        for (int i = 0; i < splitWords.length; i++) {
            list.add(splitWords[i]);
        }
    }

    public String getPreviousWords(int n, int maxCharacterLength) {
        StringBuilder strBuilder = new StringBuilder();
        int characterCount = 0;
        int itemSize = 0;
        // you need to check this negative or not
        if(firstWordIndex < 0)
            firstWordIndex = 0;
        ListIterator<String> nextIter = list.listIterator(firstWordIndex);
        while (nextIter.hasPrevious() && itemSize < n) {
            String elem = (String) nextIter.previous();
            characterCount += elem.length();
            if (characterCount > maxCharacterLength) {
                break;
            }
            strBuilder.insert(0, elem + " ");
            itemSize++;
        }

        if(firstWordIndex == 0) {
            firstWordIndex = 0;
            nextWordIndex = itemSize;
        }
        nextWordIndex = firstWordIndex;
        firstWordIndex-=itemSize;

        return strBuilder.toString();
    }

    /**
     * Obtains the next n number of words given the maximum number of characters
     * that can fit on the screen. If not all words fit on the screen
     *
     * @param n
     *            number of words
     * @param maxCharacterLength
     *            of text that can fit on the screen.
     * @return next words
     */
    public String getNextWords(int n, int maxCharacterLength) {
        StringBuilder strBuilder = new StringBuilder();
        int characterCount = 0;
        int itemSize = 0;
        ListIterator<String> nextIter = list.listIterator(nextWordIndex);
        while (nextIter.hasNext() && itemSize < n) {
            String elem = (String) nextIter.next();
            characterCount += elem.length();
            if (characterCount > maxCharacterLength) {
                break;
            }
            strBuilder.append(elem);
            strBuilder.append(" ");
            itemSize++;
        }
        firstWordIndex = nextWordIndex;
        nextWordIndex+=itemSize;
        return strBuilder.toString();

    }
}
公共类Test2{
公共静态void main(字符串[]args){
test2t=新的Test2();
t、 createTokens();
字符串nextWords=t.getNextWords(5,30);
System.out.println(“句子:“+nextWords”);
字符串nextWords2=t.getNextWords(5,30);
System.out.println(“句子:“+nextWords2”);
字符串nextWords3=t.getNextWords(5,30);
System.out.println(“句子:“+nextWords3”);
字符串previousWords=t.getPreviousWords(3,10);
System.out.println(“上一句:“+上一句话”);
previousWords=t.getPreviousWords(3,10);
System.out.println(“上一句:“+上一句话”);
previousWords=t.getPreviousWords(3,10);
System.out.println(“上一句:“+上一句话”);
previousWords=t.getPreviousWords(3,10);
System.out.println(“上一句:“+上一句话”);
previousWords=t.getPreviousWords(3,10);
System.out.println(“上一句:“+上一句话”);
nextWords=t.getNextWords(5,30);
System.out.println(“句子:“+nextWords”);
}
静态字符串text=“我是一只猫,坐在垫子上,像胖子一样大喊大叫”;
私有静态列表=新建LinkedList();
//下一句开头的索引(即当前显示的句子结尾)
静态int nextWordIndex=0;
//正在显示的当前句子的第一个单词的索引。
静态int firstWordIndex=0;
公共void createTokens(){
String[]splitWords=text.split(“”);
for(int i=0;imaxCharacterLength){
打破
}
strBuilder.insert(0,元素+“”);
itemSize++;
}
if(firstWordIndex==0){
firstWordIndex=0;
nextWordIndex=项目大小;
}
nextWordIndex=firstWordIndex;
firstWordIndex-=项目大小;
返回strBuilder.toString();
}
/**
*获取给定最大字符数的下n个字数
*如果不是所有的单词都能在屏幕上显示的话
*
*@param n
*字数
*@param maxCharacterLength
*可以在屏幕上显示的文本的数量。
*@返回下一个单词
*/
公共字符串getNextWords(int n,int maxCharacterLength){
StringBuilder strBuilder=新StringBuilder();
int characterCount=0;
int itemSize=0;
ListIterator nextIter=list.ListIterator(nextWordIndex);
while(nextIter.hasNext()&&itemSizemaxCharacterLength){
打破
}
strBuilder.append(elem);
strBuilder.append(“”);
itemSize++;
}
firstWordIndex=nextWordIndex;
nextWordIndex+=项目大小;
返回strBuilder.toString();
}
}
输出:

句子:我是一只猫谁句子:坐在垫子上和句子:大叫 作为前一句话的人:垫子和前一句话: 谁坐在前一句:我是一只猫前一句:我 我是一只猫谁


如果您将字符串拆分一次并使用
数组.asList(array)
包装,然后使用
List.sublist
提取所需的单词片段,这将是最简单的。@AndyTurner这肯定会使问题得到解决。我不明白您想要什么,你能更好地解释一下吗?不要把一个建议作为回答,它仍然会有同样的问题,因为即使我迭代hasNext和hasPrev。hasPrev=HASPNEXT,只要方向上有开关。意思是,仍然要跟踪显示的文本的初始索引和最后索引。我想这不是什么大问题。我已经在代码中发布了评论,你需要检查这行输出:句子:一二三四五句:一二三四五句:一二三四五缺失:currentWordIndex+=项目大小;在getNext中:)输出:句子:一二三四五
Sentence: one two three four five
Sentence: six seven eight nine ten 
Sentence: eleven twelve thirteen fourteen 
Sentence: ten nine eight seven six 
public class Test2 {

    public static void main(String[] args) {
        Test2 t = new Test2();
        t.createTokens();
        String nextWords = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords);
        String nextWords2 = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords2);
        String nextWords3 = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords3);

        String previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);
        previousWords = t.getPreviousWords(3, 10);
        System.out.println("Previous Sentence: " + previousWords);

        nextWords = t.getNextWords(5, 30);
        System.out.println("Sentence: " + nextWords);
    }


    static String text = "I am a cat who sat on a mat and yelled as someone who was fat";

    private static List<String> list = new LinkedList<String>();

    // index of the start of the next sentence (i.e also the end of the sentence that is currently being displayed)
    static int nextWordIndex = 0;
    // index of the first word of the current sentence being displayed.
    static int firstWordIndex = 0;

    public void createTokens() {
        String[] splitWords = text.split(" ");
        for (int i = 0; i < splitWords.length; i++) {
            list.add(splitWords[i]);
        }
    }

    public String getPreviousWords(int n, int maxCharacterLength) {
        StringBuilder strBuilder = new StringBuilder();
        int characterCount = 0;
        int itemSize = 0;
        // you need to check this negative or not
        if(firstWordIndex < 0)
            firstWordIndex = 0;
        ListIterator<String> nextIter = list.listIterator(firstWordIndex);
        while (nextIter.hasPrevious() && itemSize < n) {
            String elem = (String) nextIter.previous();
            characterCount += elem.length();
            if (characterCount > maxCharacterLength) {
                break;
            }
            strBuilder.insert(0, elem + " ");
            itemSize++;
        }

        if(firstWordIndex == 0) {
            firstWordIndex = 0;
            nextWordIndex = itemSize;
        }
        nextWordIndex = firstWordIndex;
        firstWordIndex-=itemSize;

        return strBuilder.toString();
    }

    /**
     * Obtains the next n number of words given the maximum number of characters
     * that can fit on the screen. If not all words fit on the screen
     *
     * @param n
     *            number of words
     * @param maxCharacterLength
     *            of text that can fit on the screen.
     * @return next words
     */
    public String getNextWords(int n, int maxCharacterLength) {
        StringBuilder strBuilder = new StringBuilder();
        int characterCount = 0;
        int itemSize = 0;
        ListIterator<String> nextIter = list.listIterator(nextWordIndex);
        while (nextIter.hasNext() && itemSize < n) {
            String elem = (String) nextIter.next();
            characterCount += elem.length();
            if (characterCount > maxCharacterLength) {
                break;
            }
            strBuilder.append(elem);
            strBuilder.append(" ");
            itemSize++;
        }
        firstWordIndex = nextWordIndex;
        nextWordIndex+=itemSize;
        return strBuilder.toString();

    }
}