;----------------------------------------------------------------------------- ; ; find_substring.ncl -- Find the leftmost occurrence of a substring ; within another string. ; ; This is like Fortran's "index" string function. ; ; 2007-feb-06 Original version. By Dave Allured. ; 2007-mar-05 Name change to find_substring.ncl. ; 2008-oct-20 Fix mistake in comment. ; ; Usage: ind = find_substring (string1, string2) ; ; Input: string1 = main string to be searched ; string2 = substring to find ; ; Output: ind = integer index (zero based) of the first character of ; the substring, within the main string. ; If the substring is not found, then a negative value is ; returned. ; ; General notes: ; ; String comparisons are CASE SENSITIVE. ; Blanks in both input strings are significant, including leading ; and trailing blanks. ; ; Organization: ; University of Colorado, CIRES Climate Diagnostics Center (CDC) ; NOAA/ESRL/PSD, Climate Analysis Branch (CAB) ; ;---------------------------------------------------------------------------- function find_substring (string1[1]:string, string2[1]:string) local main, sub, len1, len2, i begin main = stringtochar (string1) ; must convert inputs to char arrays sub = stringtochar (string2) len1 = dimsizes (main) - 1 len2 = dimsizes (sub) - 1 do i = 0, len1 - len2 ; do for each possible initial offset if ( all (main(i:i+len2-1) .eq. sub(0:len2-1)) ) then return (i) ; substring found, return index end if end do return (-1) ; substring not found, return fail code end