将索引存储在数组中

时间:2011-04-04 20:10:16

标签: java arrays string

我需要帮助我如何存储句子中出现的特定单词的索引。 我需要将索引存储在一个数组中,以便以后可以访问它。我正在使用while循环,但它不起作用。

while (index > 0) {

            for (int i = 0; i < data.length; i++) {

                data[i] = index;

            }

            System.out.println("Index : " + index);


            index = input.indexOf(word, index + word.length());

        }

3 个答案:

答案 0 :(得分:0)

我在下面评论了您的代码。请阅读评论以便理解。

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());
}

ArrayList替换数据数组和关联的循环。对您找到的每个索引使用ArrayList.add()

答案 1 :(得分:0)

如果您尝试生成字符串中单词索引的列表,请尝试使用indexOf(String str, int fromIndex)重载(来自the Java API)。

编辑:另请查看此问题:Stack Overflow: Java Counting # of occurrences of a word in a string

答案 2 :(得分:0)

如果你问的是你会使用的结构类型,那么我建议使用字符串Map(单词名称)到整数列表(这些单词的索引)。

下面的课程展示了我如何实现地图存储列表。



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

在你的情况下,你会有一个单词到索引列表的映射,所以你可以这样调用这个类: ListHashMap&LT;字符串,整数&GT; wordToIndexesMap = new ListHashMap&lt; String,Integer&gt;();

享受,博罗。

相关问题