我知道您想编写一个循环来删除单词之间的多个空格,但是在您的特定问题中删除空格的最佳方法是使用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