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

标签 c pointers dynamic-memory-allocation

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

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/

相关文章:

c - 用递归程序计算矩阵的行列式时发现的最奇怪的错误

c - 具有 `sigaction()` 的 macOS `SA_SIGINFO` 处理程序不包括 `si_pid`

c++ - 错误 LNK2001 : unresolved external symbol

c++ - C语言蓝牙paquet分析

c - 关于char指针的几个问题

c - 由于移植到不同的 gcc 版本而导致的问题

c - 毫无保留的名字

C++从函数返回指向数组的指针的正确方法

c - 队列.h : how to create list of lists/queue of queues/similar combinations?

c - 在这种情况下如何正确释放双指针的内存?