Finds the first occurrence of the null-terminated byte string pointed to by substr in the null-terminated byte string pointed to by str.The terminating null characters are not compared. The behavior is undefined if either str or substr is not a pointer to a null-terminated byte string.
$begingroup$This is a naive implementation - I know that there are algorithms like KMP
However I was trying to implement it as best as I can.
GiladGilad
$endgroup$3 Answers
$begingroup$Algorithm
- your implementation has some serious bugs and unexpected behaviour.
- If passing
String.Empty
as second parameter, it throws anIndexOutOfRangeException
- If passing the unique ending part of the first parameter appended by at least one character to the second parameter, it throws an
IndexOutOfRangeException
- If you are passing
null
as either first or second parameter aNullReferenceException
is thrown. Here it would be better to throw anArgumentNullException
by using a guard clause.
- your implementation could be improved by
- checking if
strToFind.Length > test.Length
- checking if
test.Length - i > strToFind.Length
- checking if
Naming
You shouldn't use hungarian notation. Consider to rename
strToFind
to searchForm
or searchArgument
. Refactoring
After extracting the inner loop to a separate method, removing the now unneeded
if (test[i] strToFind[0])
and implementing the above we will get I prefer the above, but you could also add
inverted as condition to the
for
loop like HeslacherHeslacher
$endgroup$$begingroup$That comment would be much better off as an XML comment, so that client code can see the documentation for the method with IntelliSense:
Another problem, is that the
str1
and str2
parameters mentioned in the comment, aren't the actual parameter names you're using. You can use paramref
for that:MSDN:
The
<paramref>
tag gives you a way to indicate that a word in the code comments, for example in a <summary>
or <remarks>
block refers to a parameter. The XML file can be processed to format this word in some distinct way, such as with a bold or italic font.Use the
<returns>
XML tag to specify a function's return value - the <summary>
tag should simply state what the function does, not cover all possible outcomes.![Strstr c return null Strstr c return null](https://images.slideplayer.com/16/5001383/slides/slide_7.jpg)
Mathieu GuindonMathieu Guindon
$endgroup$$begingroup$Mostly minor stuff:
- You have probably taken the name from the C function but
StrStr
is actually not really a good name.StartIndexOf
or similar might be better. - You could write it as an extensions method to
string
which would result in a nicer calling syntax. It would look like this then:and call it like this:
ChrisWueChrisWue
$endgroup$