我正在尝试使用指针修剪字符串(从字符串的开头和结尾删除空格)。
char* killspace(char *a)
{
char *enda = NULL;
int i = 0, spaceS = 0, spaceE = 0, bigend = 0 , out = 0, taille = strlen(a);
do
{
if (a[i] == ' ')
{
spaceS++;
}
else
{
out = 1;
}
i++;
} while (out == 0);
out = 0;
do
{
if (a[taille] == ' ')
{
spaceE++;
}
else
{
out = 1;
}
taille--;
} while (out == 0);
bigend = (spaceE + spaceS);
// new size
enda = (char *)calloc((strlen(a)-bigend), sizeof(char));
i = 0;
for (int j = spaceS; j < (strlen(a)-spaceE); j++)
{
enda[i] = a[j];
i++;
}
return(enda);
free(enda);
}
bigend
是字符串开头和结尾的空格数。
但是返回的结果有一些随机字符,例如"ýýýý««««
将起始地址更改为字符串需要 (1) 将地址发送到保存字符串作为参数的指针,以便可以更改它,或者 (2) 从函数返回指向修剪字符串的新开头的指针。后者可能是你最好的选择。下面是一个示例:
#include <stdio.h>
#include <ctype.h>
char *trimstr (char *s)
{
while (isspace(*s)) /* while space, increment pointer */
s++;
char *p = s; /* pointer to string s */
while (*p) p++; /* advance pointer to end of s */
p--; /* decrement pointer off null-term */
while (isspace(*p)) /* while space, set new end of str */
{
*p = 0;
p--;
}
return s; /* return pointer to trimmed string */
}
int main () {
char mystring[] = " some string with leading/trailing WS ";
char *p = mystring;
printf ("n Original String: '%s'nn", mystring);
p = trimstr (mystring);
printf (" Trimmed String : '%s'nn", p);
return 0;
}
输出:
$ ./bin/trimstr
Original String: ' some string with leading/trailing WS '
Trimmed String : 'some string with leading/trailing WS'
以这种方式处理问题通常会导致较短的代码,这些代码试图执行"索引随机播放"以向下移动字符串中的所有字符以覆盖前导空格。但是,"索引洗牌"没有错,您只需要对偏移量特别关注并记住也要偏移null-terminator
。
如果您对保存代码行感兴趣,可以按如下方式编写一个更紧凑的 trimstr
函数版本,尽管可读性稍差:
char *trimstr (char *s)
{
while (isspace(*s)) s++; /* while space, increment pointer */
char *p = s; /* pointer to string s */
while (*p) p++; /* advance pointer to end of s */
while (isspace(*(--p))) *p = 0; /* while space, set new end of str */
return s; /* return pointer to trimmed string */
}
情况下解决了这个问题,我在字符串的末尾放了一个限制器enda[i] = ' ';
它对我有用