hello,
for school i need to make a coding program.
but i now ran in to the following problem:
i need to get the letter sequense in a word.... like the word is: hello
it needs to see that the e is the first letter from the alfabeth and the h the second ect.
can anyone help me with solving this problem?? thanks!
Loading
AlanPosted Nov 3, 2008, 5:48 AM
That's a bit more difficult, given that letters may be duplicated and the same letter may therefore map to different positions in the word, but this should deal with it:
using System;
class Program
{
static void Main()
{
string word = "hello";
char[] chars = word.ToCharArray();
Array.Sort(chars);
int[] usedIndices = new int[chars.Length];
for (int i = 0; i < usedIndices.Length ; i++)
{
usedIndices[i] = -1;
}
for (int i = 0; i < chars.Length ; i++)
{
int index = -1;
int index2 = -1;
while(true)
{
index = word.IndexOf(chars[i], index + 1);
index2 = Array.IndexOf(usedIndices, index);
if (index2 == -1)
{
usedIndices[i] = index;
break;
}
}
Console.WriteLine("{0} is letter {1} in alphabet and letter {2} in word", chars[i], i + 1, index + 1);
}
Console.ReadLine();
}
}
nick van AlstPosted Nov 3, 2008, 9:23 AM
it is working :D thanks so much!
Nick
nick van AlstPosted Nov 3, 2008, 1:14 AM
yes i tryed the sort befor but the problem is (maby i forgot to mension) i also still need to know where the letter is in the word like that e is the first letter in the alfabeth and stands on the second place.
AlanPosted Nov 2, 2008, 5:38 PM
If I've understood that correctly, you just need to sort the characters in the array:
using System;
class Program
{
static void Main()
{
string word = "hello";
char[] chars = word.ToCharArray();
Array.Sort(chars);
for (int i = 0; i < chars.Length ; i++)
{
Console.WriteLine("{0} is letter {1}", chars[i], i + 1);
}
Console.WriteLine();
}
}
As a further refinement, you could remove duplicates (such as the two l's in hello) though I haven't done it here.