简体   繁体   English

获取java jTextArea中String文本的开始和结束位置

[英]To Get the start and end positions of String text in java jTextArea

I am implementing a spellchecker using apached lucene 3.6 Want to integrate the highlighting of mispelled words with the Highlight class using the "start" and "end" position of the words. 我正在使用相符的Lucene 3.6来实现拼写检查器。我想使用单词的“开始”和“结束”位置将拼写错误的单词的突出显示与Highlight类集成在一起。

Will like to know how to get start and end positions of text as they are entered into the jtextarea. 想要知道如何在输入到jtextarea中时获取文本的开始和结束位置。

I know will have to use keyboard and mouse event listeners. 我知道将不得不使用键盘和鼠标事件侦听器。

But how do I get the "start" and "end" position of each word in the string of text. 但是,如何获得文本字符串中每个单词的“开始”和“结束”位置。

thank you. 谢谢。

Assuming "words" are just defined as characters groups separated by spaces, you can find the index of all spaces like so: 假设“单词”仅定义为用空格分隔的字符组,则可以找到所有空格的索引,如下所示:

int index = 0;
String string = ... // get from text area
while((index = string.indexOf(' ', index)) != -1) {
   // save them      
}

You could take the resulting list of space indexes and build a list of Word objects, eliminating words of zero length (adjacent space indexes), etc. 您可以获取结果的空间索引列表并构建Word对象列表,消除零长度的单词(相邻的空间索引),等等。

You need to call getText() to get the complete text in the text area as a String. 您需要调用getText()才能以字符串形式获取文本区域中的完整文本。 Then you can get the words out of this String, check them, and also in the same step get the indices of the words and their end indices, which are simply start index+wordlength. 然后,您可以从此String中获取单词,进行检查,并在同一步骤中获得单词的索引及其结尾索引,它们只是开始索引+字长。

Could you not just get the jTextArea and split the string at spaces. 您不仅可以获取jTextArea并将字符串拆分为空格。 This would give you an array of all the "words" in the area. 这将为您提供该区域中所有“单词”的数组。

String text = jTextArea.getText();
String[] words = text.split(' ');

Then to get the index of the words you just add up the length of the word + 1 for the space. 然后,要获取单词的索引,只需将单词的长度加1加上空格即可。

int[] startIndices = new int[words.length];
int[] endIndices = new int[words.length];
int currentIndex = 0;
for (int i = 0; i < words.length; i++) {
    startIndices[i] = currentIndex;
    currentIndex += words[i].length;
    endIndices[i] = currentIndex;
    currentIndex++;
}

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

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