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 and the number of words after the last occurrence . How can I do it???
Asked
Active
Viewed 476 times
0
-
Please provide the expected output. – Andrew Clark Sep 27 '11 at 22:50
-
Oh! i forgot to mention i am working in java... – Thirsty Crow Sep 28 '11 at 00:47
3 Answers
3
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
.

x4u
- 13,877
- 6
- 48
- 58
0
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

Nasenbaer
- 4,810
- 11
- 53
- 86
0
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}

Jonas Elfström
- 30,834
- 6
- 70
- 106