Alternatives to substr without Stateflow?

9 vues (au cours des 30 derniers jours)
Erik Taurus
Erik Taurus le 9 Mai 2020
Commenté : Erik Taurus le 12 Mai 2020
I was trying to make a sub string and searched and found this.
However this seem to require Stateflow, which I don't have...
Trying to make my own way(implementation?) using
string = "This should really be in the MatLab core!";
%convert to character array
b = convertStringsToChars(string);
ba = length(b);
%get index of "in the"
k = strfind(b,"in the");
stringbuilder = "";
%start the loop from k
for cIx = k:ba
%sprintf because spaces will be ignored otherwise
stringbuilder = strcat(stringbuilder,sprintf("%s",b(cIx)));
end
disp(stringbuilder);
Result:
in the MatLab core!
---
Is there another way?

Réponse acceptée

Ameer Hamza
Ameer Hamza le 9 Mai 2020
Modifié(e) : Ameer Hamza le 9 Mai 2020
char arrays support indexing. Also, string is the name of MATLAB built-in function, so I named the name of the variable to 'str'
str = "This should really be in the MatLab core!";
%convert to character array
b = char(str); % you can simply use char()
ba = length(b);
%get index of "in the"
k = strfind(b,"in the");
stringbuilder = b(k:end);
stringbuilder = string(stringbuilder); % convert back to string
Result
>> stringbuilder
stringbuilder =
"in the MatLab core!"
  3 commentaires
Ameer Hamza
Ameer Hamza le 10 Mai 2020
I am glad to be of help.
Erik Taurus
Erik Taurus le 12 Mai 2020
If anyone else read this I found out that MatLab does have this built in, but in three different core functions
extractbetween example:
str = "Perhaps I should read the documentation before posting questions!";
startStr = strfind(str,"I ");
endStr = strfind(str,"before")-1;
newStr = extractBetween(str,startStr,endStr);
fprintf("%s\r",newStr);

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by