【问题标题】:Extract token positions from String Array- Java从字符串数组中提取标记位置-Java
【发布时间】:2011-12-05 13:28:24
【问题描述】:

我只是想问是否有一种简单的方法可以从 java 中的字符串数组中提取字符串。 例如,如果我有输入:

String searchtext = "The one thing";
String source = "the one Thing in life is to not do in java";
String annote = "det num nn pp nn cop to neg vv pp nn";

我想要输出(我不想使用正则表达式,因为我的搜索文本会有所不同)

det num nn

这段代码能用吗????

String searchtext = "The one thing";
String source = "the one Thing in life is to not do in java";
String annote = "det num nn pp nn cop to neg vv pp nn";
String[] annotelist = annote.split(" ");

List<String> sourcelist = Array.asList(sourcetext.split(" ")); 
search_startpt = searchlist.indexof(search[0]);

String[] searchannote = annotelist[search_startpt];
for (int j=1; j<sourcelist.length(); j++) 
  searchanote[j] = annotelist[sear_startpt+j];

System.out.println(StringUtils.join(searchannoate, " "));

原来,我试过下面的代码:

import org.apache.commons.lang.StringUtils;

String searchtext = "The one thing";
String[] search  = searchtext.split(" ");
String source = "the one Thing in life is to not do in java";
String[] sourcelist  = source.split(" ");
String annote = "det num nn pp nn cop to neg vv pp nn";
String[] annotelist = annote.split(" ");

int search_startpt = 0;

for (int i=0; i<sourcelist.length(); i++) {
  if (sourcelist[i].equalsIgnoreCase(search[0])) {
    for (int j=1; j<search.length(); j++) {
      if (sourcelist[i+j].equalsIgnoreCase(search[j]) ==0) break;
      if (sourcelist[i+search.length()].equalsIgnoreCase(search[search.length()-1])) search_startpt = i;
    }
  }
}

String[] searchannote = annotelist[search_startpt];

for (int j=1; j<sourcelist.length(); j++) 
  searchanote[j] = annotelist[sear_startpt+j];

System.out.println(StringUtils.join(searchannoate, " "));

【问题讨论】:

  • 感谢 Gray,String.indexof(X) 可以找到 searchtext char 位置,但不能找到结果 searchannoate。
  • 对,对不起,没有解析完整的问题。 @solendil 的答案是正确的。

标签: java string search text arrays


【解决方案1】:

将字符串之间的所有== 替换为.equals()。示例:

if (sourcelist[i] == search[0]) {

变成

if (sourcelist[i].equals(search[0])) {

原因是当你split()一个String时,所有创建的String对象都是新的和不同的,即使它们的内容是一样的。 == 操作符测试两个引用是否指向同一个对象,而.equals() 测试两个对象是否具有相同的内容。

【讨论】:

  • 谢谢,但是有没有更短的方法可以从源文本中提取所需的字符串?
  • 您可以随时将数组转换为列表并执行 indexOf Arrays.asList(sourcelist).indexOf(search[0]);
  • 意思比split()短?不是我知道的......作为主要算法,还有很多其他解决方案。比如sourceText.index(search),那么统计这个索引之前的空格A的个数,统计搜索词中token B的个数,从annote数组中取出元素A到B。可能会更短...
  • 这行得通吗? List&lt;String&gt; sourcelist = Array.asList(source.split(" ")); 然后我做一个sourcelist.indexof(search[0]);
  • 我从List&lt;String&gt; sourcelist = Array.asList(source.split(" ")) 行收到错误The method asList(String[]) is undefined for the type Array。我该如何解决?
猜你喜欢
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 2018-10-25
  • 2020-11-28
  • 1970-01-01
相关资源
最近更新 更多