Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare last characters of strings

Tags:

string

matlab

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.

like image 633
jonie83 Avatar asked Dec 16 '14 15:12

jonie83


3 Answers

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.

like image 68
Dennis Jaheruddin Avatar answered Oct 18 '22 01:10

Dennis Jaheruddin


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
like image 3
Xiangrui Li Avatar answered Oct 18 '22 01:10

Xiangrui Li


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
like image 2
Divakar Avatar answered Oct 18 '22 01:10

Divakar