Search code examples
c#stringsubstring

Is there any way to compare strings with a startIndex?


I was just wondering if there is a way of comparing c# strings with a startIndex for the first one. I have a long string and an index and want to find if the next characters are equal to a string. The only way I have found to do this is:

public static bool Equals (string longString, int index, string compare) => longString.Substring(index, compare.Length) == compare;

I think this is inefficient because you are unnecessarily creating a substring for each time you compare a new string at the index. Is there a more efficient way? I looked at string.Equals but it doesn't look like something I would be comfortable trying to rewrite.


Solution

  • string.Compare(longString, startIndex, compare, 0, compare.Length, isIgnoreCase) == 0;
    

    Please see: https://learn.microsoft.com/en-us/dotnet/api/system.string.compare