フィルターのクリア

swap letters 2 by 2 in a string.

2 ビュー (過去 30 日間)
Mohammed
Mohammed 2012 年 11 月 12 日
how cani i swap letters 2 by 2 in a string?. (in other word: abcdefg would become badcfeg)

回答 (3 件)

Matt Fig
Matt Fig 2012 年 11 月 12 日
編集済み: Matt Fig 2012 年 11 月 12 日
S = 'abcdefg'
S = S([2 1 4 3 6 5 7])
Or, generally:
for ii=1:2:numel(S)-mod(numel(S),2),S([ii,ii+1])=S([ii+1,ii]),end
  2 件のコメント
Mohammed
Mohammed 2012 年 11 月 13 日
it works, but the for loop make the string repeat 9 times!
Matt Fig
Matt Fig 2012 年 11 月 13 日
編集済み: Matt Fig 2012 年 11 月 13 日
What do you mean it repeats 9 times? When I run that FOR loop then type:
>> S
S =
badcfeg
No repeating 9 times here. Do you mean that it displays several times during the loop? Simply put a semicolon in after the assignment in the loop. I left it out so you could see what was going on. I assumed you would know to put it back in if you wanted to do so. I.e., instead of:
S([ii,ii+1])=S([ii+1,ii]),
use:
S([ii,ii+1])=S([ii+1,ii]); % Notice the ; instead of ,
Incidentally, I like this one better:
for ii=2:2:numel(S),S([ii-1,ii])=S([ii,ii-1]);end

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


Sean de Wolski
Sean de Wolski 2012 年 11 月 12 日
str = 'a':'g';
eo = mod(numel(str),2); %even odd
str(1:end-eo) = flipud(reshape(str(1:end-eo),2,[])) %swap

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 11 月 12 日
編集済み: Azzi Abdelmalek 2012 年 11 月 12 日
s='abcdefg';
m=fix(numel(s)/2)*2
s(1:m)=reshape(flipud(reshape(s(1:m),2,[])),1,[])

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by