How do I find the first of the shortest words in a sentence?
2 ビュー (過去 30 日間)
古いコメントを表示
I have defined the string variable s = "The quick brown fox jumps over the lazy dog"
Now I need to define a second string variable s1 that computes and displays the first of the shortest words in the sentence s.
This would be "The" in this case, but of course it should work with any sentence.
I am very much a beginner, so any help is appreciated! No loops please, as we are not allowed to use them yet.
Thank you!
3 件のコメント
Jan
2022 年 3 月 18 日
This sounds like a homework question. It would not be useful, if the forum solves your homework, because this would prevent, that you learn how to write code.
Please post, what you have tried so far and ask a specific question concerning your code.
採用された回答
DGM
2022 年 3 月 18 日
You're not too far off. Tools like min(), max(), find(), etc support the output of the associated index.
s = "The quick brown fox jumps over the lazy dog"
s0 = strsplit(s)
l = strlength(s0)
[minlen minidx] = min(l) % get the index of the first element with the smallest value
s1 = s0(minidx) % get the substring associated with that index
その他の回答 (1 件)
Jan
2022 年 3 月 18 日
You are on the right track.
len = strlength(s0); % Better then "l" to avoid confusion with "1"
min(len)
This replies the minimal length of the strings. But yot do not need the length, but the index. Then read the documentation:
doc min
to find out, that you need the 2nd output argument:
[minlen, index] = min(len);
% ^^^^^
The next line:
s1 = string(min(len))
would convert the minimalstring length to a string. But you want to get the substring stored in s0 with the determined index.
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!