交换字符串元胞数组中的两个字符

Swap two characters in the cell array of strings

我有一个字符串元胞数组,我想按元胞数组的百分比交换 A 和 B,例如元胞数组中字符串总数的 20%、30% 例如:

 A_in={ 'ABCDE'
        'ACD'
        'ABCDE'
        'ABCD'
        'CDE' }; 

现在,我们需要在 A 中 40% 的序列(2/5 序列)中交换 A 和 B。有些序列不包含 A 和 B 所以我们跳过它们,我们将交换包含 AB 的序列。 A 中的拾取序列是随机选择的。我适当的人可以告诉我如何做到这一点。预期输出为:

  A_out={ 'ABCDE'
          'ACD'
          'BACDE'
          'BACD'
          'CDE' }

您可以使用 strfind,例如:

A_in={ 'ABCDE';
    'ACD';
    'ABCDE';
    'ABCD';
    'CDE' };
ABcells = strfind(A_in,'AB');
idxs = find(~cellfun(@isempty,ABcells));
n = numel(idxs);
perc = 0.6;
k = round(n*perc);
idxs = randsample(idxs,k);
A_out = A_in;
A_out(idxs) = cellfun(@(a,idx) [a(1:idx-1) 'BA' a(idx+2:end)],A_in(idxs),ABcells(idxs),'UniformOutput',false);

randsample获取随机precent索引并用strrep交换

% Input
swapStr = 'AB';   
swapPerc = 0.4; % 40%

% Get index to swap
hasPair = find(~cellfun('isempty', regexp(A_in, swapStr)));
swapIdx = randsample(hasPair, ceil(numel(hasPair) * swapPerc));

% Swap char pair
A_out = A_in;
A_out(swapIdx) = strrep(A_out(swapIdx), swapStr, fliplr(swapStr));