2

I'm trying to search for a string in a string array in C# but I'm not sure how. So, if the array has 50 elements, most of them null, how would I go about searching for a string in the array? For example:

string[] this_array;
this_array = new string[50];
this_array[1] = "One, Two, Three";
this_array[2] = "Foo, Bar, Five";
this_array[3] = null;

How would I go about searching for "Five" in this_array? I understand I have to use a for loop, I'm just not sure of the actual code. I have to find the exact index so I cannot obtain a boolean.

Any help would be much appreciated!
Jamie

Update: Here's my, very incomplete code, so far:

for (array_number = 1; array_number < this_array.Length; array_number++)
{
  //no idea what to put here :S
}
4
  • 8
    What have you tried so far? Is this home work? Have you tried using a for loop? If yes, where exactly are you stuck? :) Commented Sep 14, 2011 at 12:59
  • Why do you have multiple values in a single element of the array. That is a horrible design decision. Commented Sep 14, 2011 at 13:04
  • I feel you haven't actually bothered searching on a search engine for this sort of problem before posting. I've just typed in a question in google about finding text in a string and I'm swimming in correct results. You should also look up how a for loop works. Commented Sep 14, 2011 at 13:07
  • I admit it's horrible but I'm very new to C#. And yes, it's homework. Commented Sep 14, 2011 at 13:08

5 Answers 5

2

Use Linq. It's the easiest and less error prone way.

Add a using statement to the top:

using System.Linq;

And search like this.

var result = this_array.Where(x => x != null && x.Contains("string to compare"));

if (result != null) System.Writeln(result.First());
Sign up to request clarification or add additional context in comments.

7 Comments

OP is looking for a "contains" search not an exact search
Works only where the whole string matches the search string - would not find "Five", as described in the question.
@pstrjds: C# 3.0 != .NET 3.0. C# 3 release coincided with .NET 3.5, which does include LINQ.
downvoted because is does not answer the question and uses Linq, which (unless I am mistaken) is not available in .Net 3.0, which this question is clearly tagged as and is even stated in the question title.
@Marc My bad, I just googled and saw you are correct about that. I thought the C# 3.0 equated to .Net 3.0. Glad there is consistency in the numbering :) The answer still doesn't handle the contains portion of the question though.
|
1

Here is some sample code for you. This will find the first index for a matching entry.

int foundIndex = -1;
for(int i=0; i < this_array.Length; ++i)
{
    if (!string.IsNullOrEmpty(this_array[i]) && this_array[i].Contains(searchString))
    {
        foundIndex = i;
        break;
    }
}

Comments

0

You could try this...

int index = -1;
string find = "Five";

for(int i = 0; i < this_array.Length; i++)
{
   if(string.IsNullOrEmpty(this_array[i]))
      continue;
   if(this_array[i].ToLowerInvariant().Contains(find.ToLowerInvariant()))
   {
      index = i;
      break;
   }
}

NOTE: My search is case-insensitive. If you care about the casing of characters the remove both instances of .ToLowerInvariant()

7 Comments

you would probably want to perform the ToLowerInvariant on the find string as well.
Why on earth would you not just add (!string.IsNullOrEmpty(this_array[i])) to the Contains conditional. Of course there are better ways like Fabio suggested. I have to vote this down because of the poor techique.
@pstrjds, thanks I meant to put that but must have forgot by the time I typed all the rest (need Intellisense here!)
Thanks @musefan but that didn't seem to work - it processes fine (i.e. there aren't any errors outputted) but it doesn't find the string.
If you do care about this remaining case-insensitive, it would be a good idea to perform the ToLowerInvariant on the find string outside the bounds of the for loop, since it's value is constant throughout the loop. There is no need to repeatedly perform that operation in the loop.
|
0

Since this was homework, I'd recommend you familiarize yourself with the methods available in the String class:

String Methods

MSDN is your friend.

Comments

-1
for(int i=1;i<this_array.length;i++)
    if(this_array[i]!=null)
        if(this_array[i].indexOf("Five")>-1
            return i;

That is roughtly c# code - I may have made some minor errors. But surely you could achieve this yourself. Also, I think there are probably better ways of doing this.

2 Comments

doesnt compile, and if it did you could hit an index out of bounds error with the wrong search string
it is only rough. And it will sort of work. It was the quickest way of typing it. It should point towards the right solution.

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.