フィルターのクリア

How can I split a string and assign new values to the strings?

2 ビュー (過去 30 日間)
JVM
JVM 2017 年 1 月 9 日
コメント済み: the cyclist 2017 年 1 月 9 日
If if want to change the string
str='Hello'
Into a new string with the values
str='Hotel-Echo-Lima-Lima-Oscar'
How do I do that?

採用された回答

Guillaume
Guillaume 2017 年 1 月 9 日
編集済み: Guillaume 2017 年 1 月 9 日
This is even simpler, using the newly introduced replace (R2016b):
natoLookup = {'h','Hotel-';
'e','Echo-';
'l','Lima-';
'o','Oscar-';
};
replace(lower('Hello'), natoLookup(:, 1), natoLookup(:, 2))
  1 件のコメント
the cyclist
the cyclist 2017 年 1 月 9 日
Oooh, nice!
Please unaccept my answer and accept this one!

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

その他の回答 (2 件)

the cyclist
the cyclist 2017 年 1 月 9 日
編集済み: the cyclist 2017 年 1 月 9 日
Here is one way:
natoLookup = {'h','Hotel-';
'e','Echo-';
'l','Lima-';
'o','Oscar-';
};
str = 'Hello';
newstr = '';
for nc = 1:numel(str)
[tf,loc] = ismember(lower(str(nc)),natoLookup(:,1));
newstr = [newstr,natoLookup{loc,2}];
end
% Trim the excess hyphen
newstr(end) = [];
  3 件のコメント
Image Analyst
Image Analyst 2017 年 1 月 9 日
If you modify natoLookup to include every character you want to replace (the whole alphabet plus symbols) and change str to be whatever word you want to operate on, then it will be completely general.
the cyclist
the cyclist 2017 年 1 月 9 日
As @ImageAnalyst states, it will be general after you generalize the lookup table.
One other quick comment: If you are planning to use this with very long text, it would be best to modify this code to preallocate memory for newstr. The current algorithm will manage memory poorly.

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


Stephen23
Stephen23 2017 年 1 月 9 日
編集済み: Stephen23 2017 年 1 月 9 日
Using indexing means no loops and a very memory-efficient method:
>> str = 'Hello World!';
>> tmp = num2cell(str);
>> idx = isletter(str);
>> C = {'Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whiskey', 'Xray', 'Yankee', 'Zulu'};
>> tmp(idx) = strcat(C(1+upper(str(idx))-'A'),'-');
>> [tmp{:}]
ans = Hotel-Echo-Lima-Lima-Oscar- Whiskey-Oscar-Romeo-Lima-Delta-!
Or with a bit of attention to the hyphens:
>> D = {'','-'};
>> idy = idx & [idx(2:end),false];
>> tmp(idx) = strcat(C(1+upper(str(idx))-'A'),D(1+idy(idx)));
>> [tmp{:}]
ans = Hotel-Echo-Lima-Lima-Oscar Whiskey-Oscar-Romeo-Lima-Delta!

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by