替换包含'#'的每个字符串

时间:2018-04-29 19:22:11

标签: matlab

我有一个包含像下面的dataT1这样的字符串的单元格数组。如何替换包含'#'的所有字符串?随着字母' O'没有别的(字符串中没有数字)?

dataT1 = {

    [275.7770]    [169.6630]    [89.5380]    [48.2740]    [24.2400]    [12.7510]
    [284.3560]    [160.4500]    [87.3740]    [47.4500]    [23.9530]    [12.4590]
    '# 12.304'    [129.7730]    [66.2630]    [34.1540]    [15.1730]    [ 9.6840]
    [267.5270]    [152.3700]    '# 17.504'    [45.2510]    [23.3770]    [13.0670]
    [206.9110]    [115.3030]    [56.4770]    [29.9350]    [14.8680]    '# 6.504' }

1 个答案:

答案 0 :(得分:1)

您可以使用简单的循环。

如果您想将#替换为O,请使用以下内容:

for c = 1:numel(data)
    % check for character array type in case cell also has numeric values
    if ischar(data{c})
        % replace hashes with 'O'
        data{c} = strrep(data{c}, '#', 'O');
    end
end

如果您想仅使用字符串#替换包含'O'的整个字符串,请使用此字符:

for c = 1:numel(data)
    % check for character array type in case cell also has numeric values
    if ischar(data{c})
        % Search for # within string
        if strfind( data{c}, '#' ) > 0
            % replace string with 'O'
            data{c} = 'O';
        end
    end
end