gpt4 book ai didi

c - 使用指针返回修剪后的字符串

转载 作者:行者123 更新时间:2023-11-30 18:40:11 26 4
gpt4 key购买 nike

我正在尝试使用指针修剪字符串(删除字符串开头和结尾的空格)。

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'\n\n", mystring);

p = trimstr (mystring);

printf (" Trimmed String : '%s'\n\n", p);

return 0;
}

输出:

$ ./bin/trimstr

Original String: ' some string with leading/trailing WS '

Trimmed String : 'some string with leading/trailing WS'

以这种方式解决问题通常会导致尝试执行“索引洗牌”以将字符串中的所有字符向下移动以覆盖前导空格的代码较短。但是,“index-shuffle”没有任何问题,您只需特别注意偏移量并记住还要偏移空终止符

如果您有兴趣保存代码行,可以按如下方式编写 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 */
}

关于c - 使用指针返回修剪后的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26983120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com