I want to check whether Value1
below contains \"abc\" within the first X characters. How would you check this with an if
statement?
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);
You're close... but use:
if (Value1.StartsWith("abc"))
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);
}
}
This is what you need :
if (Value1.StartsWith("abc"))
{
found = true;
}
Use IndexOf is easier and high performance.
int index = Value1.IndexOf("abc");
bool found = index >= 0 && index < x;