从就地一字符串中去除空白? [英] Strip whitespace from a string in-place?
问题描述
我在的采访问题清单看到这个。让我疑惑。
I saw this in a "list of interview questions". Got me wondering.
不限于空白字符必须地,当然,很容易推广到除去从字符串,就地某些特定的字符。
Not limited to whitespace necessarily, of course, easily generalized to "removing some specific character from a string, in-place".
我的解决办法是:
void stripChar(char *str, char c = ' ') {
int x = 0;
for (int i=0;i<strlen(str);i++) {
str[i-x]=str[i];
if (str[i]==c) x++;
}
str[strlen(str)-x] = '\0';
}
我怀疑有一个更有效的,但有一个解决方案,更优雅?
I doubt there is one more efficient, but is there a solution that is more elegant?
修改:完全忘了我离开的strlen
在那里,这是最绝对不是有效的。
edit: totally forgot I left strlen
in there, it is most definitely not efficient
推荐答案
首先, I&LT;的strlen(STR)
始终是遍历字符串低效的成语。正确的循环条件简直是海峡[I]
,即循环,直到海峡[I]
是空终止。
First of all, i<strlen(str)
is always an inefficient idiom for looping over a string. The correct loop condition is simply str[i]
, i.e. loop until str[i]
is the null terminator.
随着中说,这里是最简单/最简洁的算法,我才知道:
With that said, here's the simplest/most concise algorithm I know:
for (size_t i=0, j=0; s[j]=s[i]; j+=!isspace(s[i++]));
注意:我的解决方案是相对于身体(特定字符)写在主题(空格)的问题。如果需要,可以轻松适应它。
Note: My solution is for the question as written in the subject (whitespace) as opposed to the body (particular character). You can easily adapt it if needed.
这篇关于从就地一字符串中去除空白?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!