C-Style String Searching In R

Below are two functions, strstr and nstrtstr which provide a string- searching interface which is similar to that of the strstr function in C. They are only designed to be used on small strings. For large strings they may be quite slow.

########################################################################################################
# Some C-style string searching functions, because I'm not very good at using regular expressions ;-)

# Returns the index where needle is found in haystack or zero if not found.
nstrstr <- function(haystack,needle)
{
  lenHaystack <- nchar(haystack)
  lenNeedle   <- nchar(needle)
  if (lenHaystack < lenNeedle)
    return (0)
  if (lenHaystack == lenNeedle)
    return(haystack==needle)
  lenDiff <- lenHaystack-lenNeedle
  for (i in (1:lenDiff))
    if (needle==substr(haystack,i,i+lenNeedle-1))
      return(i)

  return (0)
}

strstr <- function(haystack,needle)
{
  strIndex <- nstrstr(haystack,needle)
  if (strIndex==0)
    return ("")
  return (substr(haystack,strIndex,nchar(haystack)))
}

#####################################################################################################