Removing A String Prefix
QUESTION: Does anyone know a fast way to remove the same prefix from all the elements in a string array? For example, suppose I start with this string array:
array = ['dog.spot', 'dog.rover', 'dog.lucky']
I want to end up with this:
final_array = ['spot', 'rover', 'lucky']
The only way I know to do this is with a FOR loop and the STRSPLIT(array[i], '.', /EXTRACT) command. Is there a more efficient way without a loop?
![]()
ANSWER: The answer is provided by JD Smith.
For a fixed-length string like this, it is easy:
IDL> array = ['dog.spot', 'dog.rover', 'dog.lucky']
IDL> final_array = StrMid(array, 4)
IDL> Print, final_array
spot rover lucky
But, suppose it is a non-uniform length string:
IDL> array = ['dog.spot','cat.betsy','doggy.rover','parrot.bill','dog.lucky']
IDL> p = StrPos(array, '.')
IDL> final_array = StrMid(array, 1#p+1)
IDL> Print, final_array
spot betsy rover bill lucky
Notice that silly use of 1#p. This is to ensure that only one substring is extracted from each string in the array. (Try it without the 1# and you will see what I mean. Have a close look at the STRMID documentation or, for a more comprehensible explanation, this article.)
Or you could even be more general and use a regular expression:
IDL> array = ['dog.spot','cat*betsy','doggy#rover','parrot&bill','dog@lucky']
IDL> p = StRegEx(array,'^.+[.*#&@]', LENGTH=len)
IDL> final_array = StrMid(array, 1#len)
IDL> Print, final_array
spot betsy rover bill lucky
![]()
Copyright © 2007 David W. Fanning
Last Updated 2 April 2007