I would like to get only the begining of string , is there an equivalent matlab that allows to say : startsWith('It-is') like in java?
Thanks
I would like to get only the begining of string , is there an equivalent matlab that allows to say : startsWith('It-is') like in java?
Thanks
You can use the strfind
function to tell if one string starts with another. The function returns the starting index of each occurrence of the string you're looking for, or an empty array if the string is not found.
S = 'Find the starting indices of the pattern string';
strfind(S, 'It-is')
If the string started with 'It-is'
then the first index of the array returned by strfind
would be 1 (i.e. the index of the first character).
For long strings, it is faster to do this
s = (numel(a)>=numel(b)) && all(a(1:min(numel(a),numel(b)))==b(1:min(numel(a),numel(b))));
in order to have the equivalent to a.startsWith(b)
.
The option that works best for me is:
~isempty(regexp(s, '^It-is', 'once'))
The ~isempty allows you to use the expression with logical ORs or ANDs like this:
if ~isempty(regexp(s, '^It-is', 'once')) || ~isempty(regexp(s, '^It-was', 'once'))
The 'once' parameter is an optimization to ensure you don't keep scanning the string once you have found the match at the beginning.
The trouble with strfind is that it returns a non-scalar result, which limits where you can use it. More straightfoward would be to use regexp like so,
s = 'It-is true.';
if regexp(s, '^It-is')
disp('s starts with "It-is"')
end
isempty(strfind(s, regexp)
is always true, because strfind returns {[]}
if it haven't found a match. –
Profit if regexp(s, '^It-is')
gives a error: > "Conversion to logical from cell is not possible" –
Profit >> s = 'It-is true.'; if regexp(s, '^It-is') disp('s starts with "It-is"') end
outputs: s starts with "It-is"
In the example s is not a cell. Can you provide the context in which you encountered the error? –
Bisulfate I want to add that if s is a cell then regexp and strfind return a cell array.
You can use one of two variants in this case:
pos = strfind(s, 'It-iss');
if (~isempty(pos{1,1}))
disp('s starts with "It-is"')
end
or
pos = regexp(s, '^It-is');
if (~isempty(pos{1,1}))
disp('s starts with "It-is"')
end
You can't directly cast the return value of regexp
or strfind
to bool, because they return If there are no matches, regexp
and strfind
return a cell array with empty cell {[]}
. To access the first cell you need to us ecurled braces operator pos{1,1}
.
Starting in Matlab2016b, there is a startsWith function:
startsWith(your_string, 'It-is')
In previous versions, you can use Bill the Lizard's answer to make your own function:
matches = strfind(your_string, 'It-is');
string_starts_with_pattern = ~isempty(matches) && matches(1) == 1;
© 2022 - 2024 — McMap. All rights reserved.
strfind
in anisempty
to get a boolean. Also good to keep in mind that the MATLAB implementation ofregexp
is much much slower thanstrfind
. – Cambist