【问题标题】:How can I concatenate strings in a cell array with spaces between them in MATLAB?如何在 MATLAB 中连接元胞数组中的字符串,它们之间有空格?
【发布时间】:2011-07-14 15:03:57
【问题描述】:

我想连接(用空格填充)元胞数组{'a', 'b'} 中的字符串以提供单个字符串'a b'。如何在 MATLAB 中做到这一点?

【问题讨论】:

    标签: string matlab whitespace concatenation cell


    【解决方案1】:

    您可以作弊,将元胞数组用作 sprintf 函数的一组参数,然后使用 strtrim 清理多余的空格:

     strs = {'a', 'b', 'c'};
     strs_spaces = sprintf('%s ' ,strs{:});
     trimmed = strtrim(strs_spaces);
    

    很脏,但我喜欢...

    【讨论】:

    • strjoin 仅适用于 Matlab R2013a 及更高版本,因此如果您使用的是旧版本,此解决方案非常好。
    • 我已经使用这种方法将变量的维度手动打印为字符串,例如"123x456x7", size_info = sprintf('%dx' , size( var ) ) 并删除最后一个字符:size_info = size_info(1:end-1);
    【解决方案2】:

    matlab 有一个函数可以做到这一点,

    参考:

    strjoin

    http://www.mathworks.com/help/matlab/ref/strjoin.html

    strjoin

    将元胞数组中的字符串连接成单个字符串

    语法

    str = strjoin(C) example
    
    str = strjoin(C,delimiter)
    

    例如:

    用空格加入单词列表

    用一个空格将单个字符串连接到字符串元胞数组 C 中。

    C = {'one','two','three'};
    
    str = strjoin(C)
    
    str =
    
    one two three
    

    【讨论】:

    • "strjoin" 最早出现在 R2013a 版本中
    【解决方案3】:

    Alex 回答的小改进 (?)

    strs = {'a','b','c'};  
    strs_spaces = [strs{1} sprintf(' %s', strs{2:end})];
    

    【讨论】:

      【解决方案4】:

      您可以使用函数 STRCAT 将空格附加到元胞数组的最后一个元胞以外的所有元胞,然后将所有字符串连接在一起:

      >> strCell = {'a' 'b' 'c' 'd' 'e'};
      >> nCells = numel(strCell);
      >> strCell(1:nCells-1) = strcat(strCell(1:nCells-1),{' '});
      >> fullString = [strCell{:}]
      
      fullString =
      
      a b c d e
      

      【讨论】:

        【解决方案5】:

        joinstrjoin 均在 R2013a 中引入。然而,the mathworks site about strjoin 写道:

        从 R2016b 开始,建议使用 join 函数来连接字符串数组的元素。

        >> C = {'one','two','three'};
        >> join(C) %same result as: >> join(C, ' ')
        
        ans = 
        
          string
        
            "one two three"
        
        >> join(C, ', and-ah ')
        
        ans = 
        
          string
        
            "one, and-ah two, and-ah three"
        

        我个人也喜欢 Alex 的解决方案,因为旧版本的 Matlab 在世界各地的研究小组中都很丰富。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-02-07
          • 2011-12-25
          • 2011-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多