Sunday, March 27, 2011

C# if string contains 'abc' within the first X characters...

Hi all, I want to check that Value1 below contains abc but only within the first X characters, how would you write the if statement to check for this?

Value1 = ddabcgghh

if (Value1.Contains(abc))
   {
       found = true;
   }

Thanks

PS It could be within the first 3,4 or 5 characters.

From stackoverflow
  • if (Value1.StartsWith("abc")) { found = true; }
    
    Will : I don't think that meets the requirements.
    Jim Anderson : Isn't that the same as found = Value1.StartsWith("abc") ?
    olle : @Will - true but as in all software projects the requirements have been changed since I had a go at it. @Jim - True but I kept the style of the author of question.
  • You're close... but use: if (Value1.StartsWith("abc"))

  • This is what you need :

    if (Value1.StartsWith("abc"))
    {
    found = true;
    }
    
  • Or if you need to set the value of found:

    found = Value1.StartsWith("abc")
    

    Edit: Given your edit, I would do something like:

    found = Value1.Substring(0, 5).Contains("abc")
    
  • shorter version;

    found = Value1.StartsWith("abc");

    sorry, but I am a stickler for 'less' code.


    Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

    public static class StackOverflowExtensions
    {
        public static bool StartsWith(this String val, string findString, int count)
        {
            return val.Substring(0, count).Contains(findString);
        }
    }
    
    Will : I think he wanted to match "1abcwhatever" and "xyabcwhatever" as well.
    keithwarren7 : he changed that after most of us had written an answer
  • A more explicit version is

    found = Value1.StartsWith("abc", StringComparison.Ordinal);
    

    It's best to always explicitly list the particular comparison you are doing. The String class can be somewhat inconsistent with the type of comparisons that are used.

  • Use IndexOf is easier and high performance.

    int index = Value1.IndexOf("abc");
    bool found = index >= 0 && index < x;
    
  • You can also use regular expressions (less readable though)

    string regex = "^.{0,7}abc";
    
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
    string Value1 = "sssddabcgghh";
    
    Console.WriteLine(reg.Match(Value1).Success);
    
  • I would use one of the of the overloads of the IndexOf method

    bool found = Value1.IndexOf("abc", 0, 7) != -1;
    

0 comments:

Post a Comment