alvas
alvas

Reputation: 122208

Extract token positions from String Array- Java

I'm just asking whether there is a simple way to extract a string out of a string array in java. For example if i've the input:

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";

I want the output (I don't want to use a regex because my searchtext will vary)

det num nn

Will this code work????

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, " "));

Originally, I've tried the code below:

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, " "));

Upvotes: 0

Views: 833

Answers (1)

solendil
solendil

Reputation: 8458

Replace all == between strings with .equals(). Example :

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

becomes

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

Reason is that when you split() a String, all created String objects are new and different, even if their content is the same. The == operator tests that two references point to the same object, while the .equals() tests whether two objects have the same content.

Upvotes: 1

Related Questions