Replacing One Character Issue

picture = '% % %'
picture = strrep(picture,picture(1),'$')
I want to replace the 1st character with a $, but it replaces all the characters with a $. I think this is because all the characters are identical. How can I fix this without changing much of the program ?

回答 (1 件)

Voss
Voss 2023 年 3 月 3 日
編集済み: Voss 2023 年 3 月 3 日

0 投票

"I want to replace the 1st character with a $"
picture = '% % %';
disp(picture)
% % %
picture(1) = '$';
disp(picture)
$ % %
Note that that replaces the first character of picture with "$" regardless of what that character was (i.e., it does not replace the first character that's "%").
picture = 'c% % %';
disp(picture)
c% % %
picture(1) = '$';
disp(picture)
$% % %

5 件のコメント

Voss
Voss 2023 年 3 月 3 日
If you actually want to replace the first character that's "%" with "$", then:
picture = '% % %';
disp(picture)
% % %
idx = find(picture == '%', 1);
if ~isempty(idx)
picture(idx) = '$';
end
disp(picture)
$ % %
picture = 'c% % %';
disp(picture)
c% % %
idx = find(picture == '%', 1);
if ~isempty(idx)
picture(idx) = '$';
end
disp(picture)
c$ % %
Kimi Raikonnen
Kimi Raikonnen 2023 年 3 月 3 日
Thanks for your help. I don't understand the difference between the 2. Is it that the 1st is more efficient since it replaces whatever the 1st character is with a $ ?
Kimi Raikonnen
Kimi Raikonnen 2023 年 3 月 3 日
Also, does disp(picture) convert picture from a string into an array ? If so, can I do this keeping it as a string ?
Kimi Raikonnen
Kimi Raikonnen 2023 年 3 月 3 日
Actually, disp is just an alternative to fprint isn't it ?
Voss
Voss 2023 年 3 月 3 日
The difference is that one replaces the first character and one replaces the first '%'.
disp does no conversion.
disp displays to the command line, yes.

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

カテゴリ

ヘルプ センター および File ExchangeWorkspace Variables and MAT Files についてさらに検索

質問済み:

2023 年 3 月 3 日

コメント済み:

2023 年 3 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by