How do I find the first of the shortest words in a sentence?

2 ビュー (過去 30 日間)
Theresia Dannbauer
Theresia Dannbauer 2022 年 3 月 18 日
コメント済み: Theresia Dannbauer 2022 年 3 月 18 日
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
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.
Theresia Dannbauer
Theresia Dannbauer 2022 年 3 月 18 日
Hello, yes you are right, this is part of my homework. Since my teacher failed to teach us anything, I am essentially teaching MATLAB to myself.
s = "The quick brown fox jumps over the lazy dog"
s0 = strsplit(s)
l = strlength(s0)
min(l)
s1 = string(min(l))
This is all I have managed in a couple of hours. s1 does not give the string "The", but "3".
Am I at least on the right track with this? Thanks!

サインインしてコメントする。

採用された回答

DGM
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"
s = "The quick brown fox jumps over the lazy dog"
s0 = strsplit(s)
s0 = 1×9 string array
"The" "quick" "brown" "fox" "jumps" "over" "the" "lazy" "dog"
l = strlength(s0)
l = 1×9
3 5 5 3 5 4 3 4 3
[minlen minidx] = min(l) % get the index of the first element with the smallest value
minlen = 3
minidx = 1
s1 = s0(minidx) % get the substring associated with that index
s1 = "The"
  1 件のコメント
Theresia Dannbauer
Theresia Dannbauer 2022 年 3 月 18 日
Thank you so much, I would have never thought I was this close!! Thanks!

サインインしてコメントする。

その他の回答 (1 件)

Jan
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.
  1 件のコメント
Theresia Dannbauer
Theresia Dannbauer 2022 年 3 月 18 日
Thank you very much!! I thought I was way off with my code, so thanks a lot for the hints!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by