0

Is there some way to do the following in C#, but I was looking and .indexOf didnt stick out to me. Does it exist, or what other method should I be using?

string t = "joke";
string sentence = "there is no joke here";
string[] array = sentence.Split(" ".ToCharArray());

//here is the kicker
int count = array.indexOf(t);
return count;

This should return 3??

1
  • You want it to be 3 because joke is the 4th word? Commented Jul 12, 2012 at 19:36

6 Answers 6

6

How about Array.IndexOf()?

var index = Array.IndexOf(array, t);
Sign up to request clarification or add additional context in comments.

Comments

1

Use Array.IndexOf

int count = Array.IndexOf(array, t);

Comments

1

Array.IndexOf is static method, so you should use it like this:

int count = Array.IndexOf(array, t);

Comments

0
int indexOfWord = Array.FindIndex(sentence.Split(' '), w => w == t);

You don't have to do Split(" ".ToCharArray()), because there are params keyword in the definition of Split method. Compiler automaticaly converts Split(' ') to Split(new char[] {' '}) for you ;)

Comments

0

You're close: Array.IndexOf is a static method within Array. So you'd have

int index = Array.IndexOf<string>(words, "no");

See the difference?

Comments

0

this will give the index of element...

int keyIndex = array.ToList().FindIndex(w => w=="joke");

3 Comments

Why take the hit of converting it to a list?
@Hexxagonal - i dont know the direct method so that i foudn this alternet way...........nothing else in it
what's that? is that a question to me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.