Reputation: 1505
Suppose you have a string ("haystack"), and a substring you want to search for ("needle"):
string haystack = "D0B11234 AM21ANP AM23AN1";
string needle = "AM21AN";
I'm looking for a way to find the index or substring after the substring being sought.
Calling IndexOf()
returns the start position of the needle, such that index = 9
in this case:
int index = haystack.IndexOf(needle);
My initial thought was to use LastIndexOf()
, but that returns the start index of the last occurrence of the needle in the haystack.
As is answered in this similar question (and probably others), if you wanted to locate the character immediately following needle
, it is required to increment index
by the length of the needle like this:
int index = haystack.IndexOf(needle);
int indexAfterNeedle = index + needle.Length;
Is there a method (existing, or perhaps easy to extend) aside from typing index + needle.Length
every time that allows you to determine the ending index of a substring?
Upvotes: 11
Views: 6545
Reputation: 151740
No, there's nothing built into the BCL.
It's trivial to add yourself through an extension method:
public static int EndIndexOf(this string source, string value)
{
int index = source.IndexOf(value);
if (index >= 0)
{
index += value.Length;
}
return index;
}
Demo:
string testString = "D0B11234 AM21ANP AM23AN1";
string stringToSearch = "AM21AN";
int endIndex = testString.EndIndexOf(stringToSearch);
Console.WriteLine(testString);
Console.WriteLine(endIndex);
Console.WriteLine(testString.Substring(endIndex));
Output:
D0B11234 AM21ANP AM23AN1
15
P AM23AN1
This may seem like an off-by-one error depending on your requirements, so you may want to change it to index += value.Length - 1
to return the position of the last character of value
, instead of the index of the character after that.
You also may want to add an overload with an int startIndex
parameter, and actually call that one from the method above with a startIndex: 0
.
And be sure to add error handling to the extension method, like throwing an ArgumentNullException
and such.
Also, if the string to be found lies at the end of the source string, you cannot use the value returned by this method to take a substring of the source string, as it'll lie outside the source string.
Upvotes: 11
Reputation: 17785
While not using IndexOf(), if your needs may go beyond exact pattern matches, you could use a Regex:
This would allow you to do something like: What is the position of the first non-whitespace character after my search string?
string testString = "D0B11234 AM21ANP AM23AN1";
string stringToSearch = "AM21AN";
Match m = Regex.Match(testString,stringToSearch);
int endpos = m.Index + m.Length;
Match m2 = Regex.Match(testString,@"(" + Regex.Escape(stringToSearch) + @")\s*(\S)");
int nonwspos = m2.Groups[2].Index;
This returns the position of the P after your search string, but would also return the correct position even if there was whitespace after the string.
Upvotes: 2