开发者

counting number of words after last occurrence of every word in an array of strings

i am working on text. I want to find the number of words after the last occurrence of a particular word in an array of strings.For instance, String[] array={cat,rat,cat,bat,cat,cat,bat,fat,mat} and I want to find the last occurrence of every word in this array开发者_JAVA技巧 and the number of words after the last occurrence . How can I do it???


Iterate and count the array backwards and every new word that you encounter this way is the last or only instance of this word in the array. You can i.e. put the words in a hash set to check whether you have seen them already. Whenever you detect a new word this way you get the number of words behind it from the counter or by calculating array.length - currentPosition.


There is a solution with RegEx in DotNet if you will work with strings.

To search in an array here is an short example:

    using System;

class Program
{
    static void Main()
    {
    //
    // Use this array of string references.
    //
    string[] array1 = { "cat", "dog", "carrot", "bird" };
    //
    // Find first element starting with substring.
    //
    string value1 = Array.Find(array1,
        element => element.StartsWith("car", StringComparison.Ordinal));
    //
    // Find first element of three characters length.
    //
    string value2 = Array.Find(array1,
        element => element.Length == 3);
    //
    // Find all elements not greater than four letters long.
    //
    string[] array2 = Array.FindAll(array1,
        element => element.Length <= 4);

    Console.WriteLine(value1);
    Console.WriteLine(value2);
    Console.WriteLine(string.Join(",", array2));
    }
}

Also you can take a look to MSDN Example

Hope that helps Regards


In Ruby:

arr = [:cat,:rat,:cat,:bat,:cat,:cat,:bat,:fat,:mat]
hash = {}
arr.reverse.each_with_index {|item, index| hash[item]=index unless hash.has_key?(item)}
hash
=> {:mat=>0, :fat=>1, :bat=>2, :cat=>3, :rat=>7}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜