[英]C — Remove all extra spaces in string excluding chars between specified characters
我有这个字符串: print "Foo cakes are yum"
我需要以某种方式去除所有多余的空格,但在引号之间保留文本。 这是我到目前为止所拥有的:
char* clean_strip(char* string)
{
int d = 0, c = 0;
char* newstr;
while(string[c] != '\0'){
if(string[c] == ' '){
int temp = c + 1;
if(string[temp] != '\0'){
while(string[temp] == ' ' && string[temp] != '\0'){
if(string[temp] == ' '){
c++;
}
temp++;
}
}
}
newstr[d] = string[c];
c++;
d++;
}
return newstr;
}
这将返回以下字符串: print "Foo cakes are yum"
我需要能够在引号之间跳过文本,以便得到此信息: print "Foo cakes are yum"
。
这是相同的问题,但对于php,我需要交流答案: 删除字符串中的空格,不包括指定字符之间指定的空格
请帮忙。
尝试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* clean_strip(char* string)
{
int d = 0, c = 0;
char* newstr = malloc(strlen(string)+1);
int quoted = 0;
while(string[c] != '\0'){
if (string[c] == '"') quoted = !quoted;
if(!quoted && string[c] == ' '){
int temp = c + 1;
if(string[temp] != '\0'){
while(string[temp] == ' ' && string[temp] != '\0'){
if(string[temp] == ' '){
c++;
}
temp++;
}
}
}
newstr[d] = string[c];
c++;
d++;
}
newstr[d] = 0;
return newstr;
}
int main(int argc, char *argv[])
{
char *input = "print \"Foo cakes are yum\"";
char *output = clean_strip(input);
printf(output);
free(output);
return 0;
}
这将产生输出:
print "Foo cakes are yum"
它通过查找"
字符来工作。如果找到它,它将切换带quoted
的变量。如果quoted
为true,则跳过空格删除。
另外,您的原始函数永远不会为newstr分配内存。 我添加了newstr = malloc(...)
部分。 在写入字符串之前为字符串分配内存很重要。
我简化了您的逻辑。
int main(void)
{
char string[] = "print \"Foo cakes are yum\"";
int i = 0, j = 1, quoted=0;
if (string[0] == '"')
{
quoted=1;
}
for(i=1; i< strlen(string); i++)
{
if (string[i] == '"')
{
quoted = 1-quoted;
}
string[j] = string[i];
if (string[j-1]==' ' && string[j] ==' ' && !quoted)
{
;
}
else
{
j++;
}
}
string[j]='\0';
printf("%s\n",string);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.