2

I am new to programming languages. I have a requirement where I have to return a record based on a search string.

For example, take the following three records and a search string of "Cal":

  1. University of California

  2. Pascal Institute

  3. California University

I've tried String.Contains, but all three are returned. If I use String.StartsWith, I get only record #3. My requirement is to return #1 and #3 in the result.

Thank you for your help.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
Joe
  • 111
  • 1
  • 10
  • 2
    Use string.Contains, and drop the second one. If you're looking for the beginning of any word in the record, you need to `Split()` each record, and do a StartsWith on each element in the split array. – Robert Harvey Sep 27 '12 at 21:35
  • 1
    Look into string.split(), then loop through each word. – DJ Quimby Sep 27 '12 at 21:36

7 Answers7

4

If you're using .NET 3.5 or higher, I'd recommend using the LINQ extension methods. Check out String.Split and Enumerable.Any. Something like:

string myString = "University of California";
bool included = myString.Split(' ').Any(w => w.StartsWith("Cal"));

Split divides myString at the space characters and returns an array of strings. Any works on the array, returning true if any of the strings starts with "Cal".

If you don't want to or can't use Any, then you'll have to manually loop through the words.

string myString = "University of California";
bool included = false;

foreach (string word in myString.Split(' '))
{
    if (word.StartsWith("Cal"))
    {
        included = true;
        break;
    }
}
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
  • 1
    Just out of curiosity, how are newbies with Lambda expressions? I like this answer, but I'm not sure how someone New to Programming would follow it. – Dan Pichelman Sep 27 '12 at 21:39
  • It will probably confuse them a good amount I would guess. Personally I would avoid Lambdas with newbies just to keep the learning curve from being too steep, although the proposed solution is definitely a good one. – Jordan Kaye Sep 27 '12 at 21:42
  • I say it's never too early to start! But I included a for-each example just in case. – FishBasketGordo Sep 27 '12 at 21:42
  • I would recommend to start with the most readable technology available. SO why not with linq? – Tim Schmelter Sep 27 '12 at 21:51
2

You can try:

foreach(var str in stringInQuestion.Split(' '))
{
  if(str.StartsWith("Cal"))
   {
      //do something
   }
}
Lews Therin
  • 10,907
  • 4
  • 48
  • 72
  • 1
    A good answer, just make sure that you don't have a string that would satisfy this `if` statement more than once, like "California Institute of Calliopes" :) – davehale23 Sep 27 '12 at 21:47
2

I like this for simplicity:

if(str.StartsWith("Cal") || str.Contains(" Cal")){
    //do something
}
davehale23
  • 4,374
  • 2
  • 27
  • 40
0

You can use Regular expressions to find the matches. Here is an example

    //array of strings to check
    String[] strs = {"University of California", "Pascal Institute", "California University"};
    //create the regular expression to look for 
    Regex regex = new Regex(@"Cal\w*");
    //create a list to hold the matches
    List<String> myMatches = new List<String>();
    //loop through the strings
    foreach (String s in strs)
    {   //check for a match
        if (regex.Match(s).Success)
        {   //add to the list
            myMatches.Add(s);
        }
    }

    //loop through the list and present the matches one at a time in a message box
    foreach (String matchItem in myMatches)
    {
            MessageBox.Show(matchItem + " was a match");
    }
Sorceri
  • 7,870
  • 1
  • 29
  • 38
0
        string univOfCal = "University of California";
        string pascalInst = "Pascal Institute";
        string calUniv = "California University";

        string[] arrayofStrings = new string[] 
        {
        univOfCal, pascalInst, calUniv
        };

        string wordToMatch = "Cal";
        foreach (string i in arrayofStrings)
        {

            if (i.Contains(wordToMatch)){

             Console.Write(i + "\n");
            }
        }
        Console.ReadLine();
    }
  • You should provide something in addition to code, specifically please provide some information about what your code is actually doing and why it works. The OP has stated he/she is new programming, so a block of code with no comments on how it works it not going to help much. – psubsee2003 Sep 28 '12 at 00:00
0
var strings = new List<string> { "University of California", "Pascal Institute", "California University" };
var matches = strings.Where(s => s.Split(' ').Any(x => x.StartsWith("Cal")));

foreach (var match in matches)
{
    Console.WriteLine(match);
}

Output:

University of California
California University
Gromer
  • 9,861
  • 4
  • 34
  • 55
0

This is actually a good use case for regular expressions.

string[] words = 
{ 
    "University of California",
    "Pascal Institute",
    "California University"
}

var expr = @"\bcal";
var opts = RegexOptions.IgnoreCase;
var matches = words.Where(x => 
    Regex.IsMatch(x, expr, opts)).ToArray();

The "\b" matches any word boundary (punctuation, space, etc...).

Chris
  • 27,596
  • 25
  • 124
  • 225