Search code examples
stringmatlabcell-array

Change substrings in a number of strings within a cell array


I have a cell-array C with 7 strings inside C as follows:

 C =  { 'ABCDF'
'ABF'
'ABCDEFG'
'ABCDEF'
'ABDEFG'
'ABCDEFG'
'ABCEG' }

How can I change the 'AB' in each of the 3 first strings into 'BA'? The remain strings just keep the same as the original. The expected output will be as follows:

C =  { 'BACDF'
      'BAF'
      'BACDEFG'
      'ABCDEF'
      'ABDEFG'
      'ABCDEFG'
       'ABCEG' }

Solution

  • That is exactly what regexprep

    C(1:3) = regexprep(C(1:3),'AB','BA')
    

    or strrep does:

    C(1:3) = strrep(C(1:3),'AB','BA')
    

    C = 
    
        'BACDF'
        'BAF'
        'BACDEFG'
        'ABCDEF'
        'ABDEFG'
        'ABCDEFG'
        'ABCEG'