【问题标题】:Convert underscores to spaces in Matlab string?将下划线转换为 Matlab 字符串中的空格?
【发布时间】:2013-09-01 03:13:38
【问题描述】:

假设我有一个带有一些下划线的字符串,例如 hi_there。

有没有办法将该字符串自动转换为“hi there”?

(顺便说一句,原始字符串是一个变量名,我将其转换为情节标题)。

【问题讨论】:

    标签: string matlab replace


    【解决方案1】:

    令人惊讶的是还没有人提到strrep

    >> strrep('string_with_underscores', '_', ' ')
    ans =
    string with underscores
    

    应该是official way 来做一个简单的字符串替换。对于这样一个简单的案例,regexprep 是矫枉过正:是的,它们是可以做任何事情的瑞士刀,但它们带有很长的手册。 AndreasH 显示的字符串索引仅适用于替换单个字符,它不能这样做:

    >> s = 'string*-*with*-*funny*-*separators';
    >> strrep(s, '*-*', ' ')
    ans =
    string with funny separators
    
    >> s(s=='*-*') = ' '
    Error using  == 
    Matrix dimensions must agree.
    

    另外,它也适用于带字符串的元胞数组:

    >> strrep({'This_is_a','cell_array_with','strings_with','underscores'},'_',' ')
    ans = 
        'This is a'    'cell array with'    'strings with'    'underscores'
    

    【讨论】:

    • strrep 也比regexprep 快得多。
    【解决方案2】:

    试试这个 Matlab 代码的字符串变量 's'

    s(s=='_') = ' ';
    

    【讨论】:

      【解决方案3】:

      如果你不得不做更复杂的事情,比如替换多个可变长度的字符串,

      s(s == '_') = ' ' 将是一个巨大的痛苦。如果您的更换需求变得更加复杂,请考虑使用regexprep

      >> regexprep({'hi_there', 'hey_there'}, '_', ' ')
      ans = 
          'hi there'    'hey there'
      

      话虽如此,在您的情况下,@AndreasH. 的解决方案是最合适的,regexprep 是矫枉过正。

      一个更有趣的问题是,为什么要将变量作为字符串传递?

      【讨论】:

        【解决方案4】:

        regexprep() 可能是您正在寻找的,并且通常是一个方便的函数。

        regexprep('hi_there','_',' ')
        

        将采用第一个参数字符串,并用第三个参数替换第二个参数的实例。在这种情况下,它将所有下划线替换为空格。

        【讨论】:

          【解决方案5】:

          在 Matlab 中,字符串是向量,因此可以使用标准运算符来执行简单的字符串操作,例如用空格替换_。

          text = 'variable_name';
          text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
          => text = variable name
          

          【讨论】:

          • 由于双引号,这在 Matlab(可能是 Octave)中不起作用
          • 我的错。是的,我使用 Octave :)
          【解决方案6】:

          我知道这已经得到解答,但是,就我而言,我正在寻找一种方法来更正情节标题,以便我可以包含一个文件名(可能有下划线)。所以,我想用下划线打印它们,而不是作为下标显示。所以,使用上面这个很棒的信息,而不是空格,我在替换中转义了下标。

          For example:
          % Have the user select a file:
          [infile inpath]=uigetfile('*.txt','Get some text file');
          
          figure
          % this is a problem for filenames with underscores
          title(infile)
          
          % this correctly displays filenames with underscores 
          title(strrep(infile,'_','\_'))
          

          【讨论】:

          • 您好,请确保问题的答案实际上是在回答所提出的问题。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-11
          • 2022-01-03
          • 1970-01-01
          • 1970-01-01
          • 2011-07-31
          相关资源
          最近更新 更多