I need help on how I can store the indexes of a particular word occurring in a sentence. I need to store the indexes in an array so that I can access it later. I'm using a while loop but its not working.
while (index > 0) {
for (int i = 0; i < data.length; i++) {
data[i] = index;
}
System.out.println("Index : " + index);
index = input.indexOf(word, index + 开发者_C百科word.length());
}
I've commented up your code below. Please read the comments for understanding.
while (index > 0) { //String.indexOf can return a 0 as a valid answer. Use -1.
//Looping over something... Why don't you show us the primer code?
for (int i = 0; i < data.length; i++) {
/*
Looping over the `data` array.
You're filling every value of `data` with whatever is in `index`. Every time.
This is not what you want.
*/
data[i] = index;
}
System.out.println("Index : " + index);
//OK
index = input.indexOf(word, index + word.length());
}
Replace your data array and associated loop with an ArrayList
. Use ArrayList.add()
for every index you find.
If you are trying generate a list of the indices of a word in a string, try using the indexOf(String str, int fromIndex)
overload (from the Java API).
EDIT : Also check out this question: Stack Overflow: Java Counting # of occurrences of a word in a string
If you are asking about a structure type you would use then I would suggest to go with a Map of Strings (names of words) to List of Integers (indexes of these words).
The class below shows how I implemented a Map storing Lists.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Class of a map which allows to have a list of items under a single key.
* @author Konrad Borowiecki
*
* @param <T1> type of the key.
* @param <T2> type of objects the value list will store.
*/
public class ListHashMap<T1, T2> extends HashMap<T1, List<T2>>
{
private static final long serialVersionUID = -3157711948165169766L;
public ListHashMap()
{
}
public void addItem(T1 key, T2 item)
{
if(containsKey(key))
{
List<T2> tml = get(key);
tml.add(item);
}
else
{
List<T2> items = new ArrayList<T2>();
items.add(item);
put(key, items);
}
}
public void removeItem(T1 key, T2 item)
{
List<T2> items = get(key);
items.remove(item);
}
public void removeItem(T2 item)
{
Set<java.util.Map.Entry<T1, List<T2>>> set = entrySet();
Iterator<java.util.Map.Entry<T1, List<T2>>> it = set.iterator();
while(it.hasNext())
{
java.util.Map.Entry<T1, List<T2>> me = it.next();
if(me.getValue().contains(item))
{
me.getValue().remove(item);
if(me.getValue().isEmpty())
it.remove();
break;
}
}
}
}
In your case you would have a mapping of words to list of indexes so, you would call the class like this: ListHashMap<String,Integer> wordToIndexesMap = new ListHashMap<String,Integer>();
Enjoy, Boro.
精彩评论