I need to compare the last characters of strings in matlab. Natively I would do the following:
string = 'foobar';
len_string = length(string);
if len_str_2 >= 3
str_suffix = str_2(len_str_2 - 2:len_str_2);
strcmp('bar', str_suffix)
end
Is there a simpler way to do this? With strncmp
I can only compare the first n
characters.
This sounds like a typical job for a regular expression:
any(regexp('foobar','bar$')) %% Will return true
any(regexp('foobars','bar$')) %% Will return false
The dollar sign enforces the pattern to be at the end of the string.
Later Matlab has function endsWith
, but it will take me a while to start to use it due to the worry of compatibility.
str = 'foobar';
endsWith(str, 'bar') % return logical 1
You can flip left-to-right string
and search string
and then use strncmp
-
%// Inputs
string = 'foobar'
search_string = 'bar'
out = strncmp(string(end:-1:1),search_string(end:-1:1),numel(search_string))
Few sample runs -
(1) Original problem case
string =
foobar
search_string =
bar
out =
1
(2) Modified case with string
same as search_string
string =
bar
search_string =
bar
out =
1
(3) Modified case with string
of smaller length than search_string
, for which you had the IF
conditional
string =
ar
search_string =
bar
out =
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With