如何删除字符串,matlab之间的额外空格?

时间:2014-12-14 03:10:32

标签: string matlab for-loop

我已经创建了一个脚本来将文本转换为morsecode,现在我想修改它以包含单词之间的斜杠。这就像morsecode单词之间的空格斜杠空格。我知道我的循环在主循环之前是不正确的,我想修复它,如前所述,我真的需要帮助谢谢!!!:

...

Word=input('Please enter a word:','s');
  ...
             Code=MC_1;
    ...

    case ' '
         Code='/'
    otherwise 
         Valid=0;
end
if Valid
         fprintf('%s ',Code);
else
         disp('Input has invalid characters!')
         break
end

1 个答案:

答案 0 :(得分:6)

我知道您想要编写一个循环来删除单词之间的多个空格,但在特定问题中删除空格的最佳方法是使用regular expressions,特别是regexprep。正则表达式用于搜索较大字符串中的特定模式/子字符串。在这种情况下,我们试图找到的是由多个空格组成的子串。 regexprep找到与模式匹配的子字符串,并将其替换为另一个字符串。在我们的示例中,您将搜索字符串中包含至少一个空格字符的任何子字符串,并用单个空格字符替换它们。另外,我看到你使用strtrim修剪了字符串的前导和尾随空格,这很棒。现在,您需要做的只是调用regexprep

Word = regexprep(Word, '\s+', ' ');

\s+是查找至少一个空格字符的正则​​表达式。然后我们用一个空格替换它。因此,假设我们将此字符串存储在Word

Word = '   hello    how    are   you   ';

修剪前导空格和尾随空格,然后按照我们所讨论的方式调用regexprep,这样就可以了:

Word = strtrim(Word);
Word = regexprep(Word, '\s+', ' ')

Word =

hello how are you

如您所见,使用strtrim删除了前导和尾随空格,正则表达式处理其间的其余空格。


但是,如果你没有使用循环,你可以做的是使用logical变量,当我们检测到空格时设置为true,然后我们使用这个变量并跳过其他空白字符直到我们点击了一个不是空格的字符。然后我们将放置我们的空间,然后放置/,然后放置空格,然后继续。换句话说,做这样的事情:

Word = strtrim(Word); %// Remove leading and trailing whitespace
space_hit = false; %// Initialize space encountered flag
Word_noSpace = []; %// Will store our new string
for index=1:length(Word) %// For each character in our word
    if Word(index) == ' ' %// If we hit a space
       if space_hit %// Check to see if we have already hit a space
          continue; %// Continue if we have
       else
          Word_noSpace = [Word_noSpace ' ']; %// If not, add a space, then set the flag
          space_hit = true;
       end
    else
       space_hit = false; %// When we finally hit a non-space, set back to false
       Word_noSpace = [Word_noSpace Word(index)]; %// Keep appending characters
    end
end
Word = Word_noSpace; %// Replace to make compatible with the rest of your code

for Character = Word %// Your code begins here
   ...
   ...

上面的代码所做的是我们有一个名为Word_noSpace的空字符串,它将包含我们的单词,没有多余的空格,并且这些空格被一个空格替换。循环遍历每个字符,如果我们遇到空格,我们检查是否已经遇到空格。如果我们有,只需继续循环。如果我们没有,那么连接一个空格。一旦我们最终命中了非空格字符,我们只需将那些不是空格的字符添加到这个新字符串中。结果将是一个没有多余空格的字符串,并用一个空格替换。

修剪前导和尾随空格后运行上面的代码,从而得出:

Word =

hello how are you