Compares characters within strings

16 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 6 月 16 日
コメント済み: Shuoze Xu 2022 年 6 月 16 日
Hi.
I want user to input two words, and then compare The two words. If The words differ in characters: n; If they are the same, print 'same'.
Here is my code.
letter1 = input("Please enter a string: ",'s');
letter2 = input("Please enter a string: ",'s');
for i = 1:3
if (letter1(i) ~= letter2(i))
fprintf("The words differ in characters: %d\n",i)
else
fprintf("same\n");
end
end
Sample test:
Please enter a string: cat
Please enter a string: cat
same
same
same
The problem I encountered was how to print 'same' only once?

回答 (1 件)

KSSV
KSSV 2022 年 6 月 16 日
編集済み: KSSV 2022 年 6 月 16 日
letter1 = input("Please enter a string: ",'s');
letter2 = input("Please enter a string: ",'s');
count = 0 ;
for i = 1:3
if (letter1(i) ~= letter2(i))
fprintf("The words differ in characters: %d\n",i)
else
count = count+1 ;
end
end
if count == length(letter1)
fprintf("same\n");
end
The above fails if letter1 and letter2 has different lengths.
You need not to do all that, read about strcmp, isequal
  1 件のコメント
Shuoze Xu
Shuoze Xu 2022 年 6 月 16 日
Thank you, I will do that.

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

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by