如何从C中的字符串中删除最后几个字符

时间:2013-01-27 06:06:58

标签: c

我知道我可以使用substr()来获得字符串中第一个n个字符。但是,我想删除最后几个字符。使用-2-3作为C中的结束位置是否有效,就像我在Python中可以这样做一样?

5 个答案:

答案 0 :(得分:8)

您可以简单地将空终止字符放在您希望字符串结束的位置,如下所示:

int main()
{
    char s[] = "I am a string";
    int len = strlen(s);
    s[len-3] = '\0';
    printf("%s\n",s);
}

这会给你:

  

“我是一个str”

答案 1 :(得分:5)

C与Python不同;字符串索引不是“聪明的”。说str[-3]字面意思是“开头前三个字节的字符”;访问此内存是未定义的行为

如果你想将字符串的最后几个字符作为另一个字符串,那么获得指向你想要的第一个字符的指针就足够了:

char *endstr = str + (strlen(str) - 3); // get last 3 characters of the string

如果您想删除最后几个字符,只需将第k个字符设置为空(\0)即可:

str[strlen(str)-3] = 0; // delete last three characters

答案 2 :(得分:5)

这是substr()函数的可能实现,包括测试代码。请注意,测试代码不会超出边界 - 缓冲区长度短于请求的字符串或缓冲区长度为零。

#include <string.h>

extern void substr(char *buffer, size_t buflen, char const *source, int len);

/*
** Given substr(buffer, sizeof(buffer), "string", len), then the output
** in buffer for different values of len is:
** For positive values of len:
** 0    ""
** 1    "s"
** 2    "st"
** ...
** 6    "string"
** 7    "string"
** ...
** For negative values of len:
** -1   "g"
** -2   "ng"
** ...
** -6   "string"
** -7   "string"
** ...
** Subject to buffer being long enough.
** If buffer is too short, the empty string is set (unless buflen is 0,
** in which case, everything is left untouched).
*/
void substr(char *buffer, size_t buflen, char const *source, int len)
{
    size_t srclen = strlen(source);
    size_t nbytes = 0;
    size_t offset = 0;
    size_t sublen;

    if (buflen == 0)    /* Can't write anything anywhere */
        return;
    if (len > 0)
    {
        sublen = len;
        nbytes = (sublen > srclen) ? srclen : sublen;
        offset = 0;
    }
    else if (len < 0)
    {
        sublen = -len;
        nbytes = (sublen > srclen) ? srclen : sublen;
        offset = srclen - nbytes;
    }
    if (nbytes >= buflen)
        nbytes = 0;
    if (nbytes > 0)
        memmove(buffer, source + offset, nbytes);
    buffer[nbytes] = '\0';
}

#ifdef TEST

#include <stdio.h>

struct test_case
{
    const char *source;
    int         length;
    const char *result;
};

static struct test_case tests[] =
{
    {   "string",  0, ""            },
    {   "string", +1, "s"           },
    {   "string", +2, "st"          },
    {   "string", +3, "str"         },
    {   "string", +4, "stri"        },
    {   "string", +5, "strin"       },
    {   "string", +6, "string"      },
    {   "string", +7, "string"      },
    {   "string", -1, "g"           },
    {   "string", -2, "ng"          },
    {   "string", -3, "ing"         },
    {   "string", -4, "ring"        },
    {   "string", -5, "tring"       },
    {   "string", -6, "string"      },
    {   "string", -7, "string"      },
};
enum { NUM_TESTS = sizeof(tests) / sizeof(tests[0]) };

int main(void)
{
    int pass = 0;
    int fail = 0;

    for (int i = 0; i < NUM_TESTS; i++)
    {
        char buffer[20];
        substr(buffer, sizeof(buffer), tests[i].source, tests[i].length);
        if (strcmp(buffer, tests[i].result) == 0)
        {
            printf("== PASS == %2d: substr(buffer, %zu, \"%s\", %d) = \"%s\"\n",
                   i, sizeof(buffer), tests[i].source, tests[i].length, buffer);
            pass++;
        }
        else
        {
            printf("!! FAIL !! %2d: substr(buffer, %zu, \"%s\", %d) wanted \"%s\" actual \"%s\"\n",
                   i, sizeof(buffer), tests[i].source, tests[i].length, tests[i].result, buffer);
            fail++;
        }
    }
    if (fail == 0)
    {
        printf("== PASS == %d tests passed\n", NUM_TESTS);
        return(0);
    }
    else
    {
        printf("!! FAIL !! %d tests out of %d failed\n", fail, NUM_TESTS);
        return(1);
    }
}

#endif /* TEST */

函数声明应该在适当的标题中。变量sublen有助于代码在:

下完全编译
gcc -O3 -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
        -Wold-style-definition -Werror -DTEST substr.c -o substr 

测试输出:

== PASS ==  0: substr(buffer, 20, "string", 0) = ""
== PASS ==  1: substr(buffer, 20, "string", 1) = "s"
== PASS ==  2: substr(buffer, 20, "string", 2) = "st"
== PASS ==  3: substr(buffer, 20, "string", 3) = "str"
== PASS ==  4: substr(buffer, 20, "string", 4) = "stri"
== PASS ==  5: substr(buffer, 20, "string", 5) = "strin"
== PASS ==  6: substr(buffer, 20, "string", 6) = "string"
== PASS ==  7: substr(buffer, 20, "string", 7) = "string"
== PASS ==  8: substr(buffer, 20, "string", -1) = "g"
== PASS ==  9: substr(buffer, 20, "string", -2) = "ng"
== PASS == 10: substr(buffer, 20, "string", -3) = "ing"
== PASS == 11: substr(buffer, 20, "string", -4) = "ring"
== PASS == 12: substr(buffer, 20, "string", -5) = "tring"
== PASS == 13: substr(buffer, 20, "string", -6) = "string"
== PASS == 14: substr(buffer, 20, "string", -7) = "string"
== PASS == 15 tests passed

在对其他answer的评论中,cool_sops会问:

  

为什么这不起作用:memcpy(new_string, old_string, strlen(old_string) - 3; &new_string[strlen(old_string) - 3] = '\0'假设new_stringold_string都是char指针和strlen(old_string) > 3

假设您删除&,插入缺少的);,指针指向有效的非重叠位置,并且满足长度条件,则应该可以用于将旧字符串中除了最后3个字符之外的所有字符复制到新字符串中,因为您可以通过将其嵌入到某些测试代码中进行测试。它并不试图处理复制旧字符串的最后三个字符,这是问题主要似乎要问的问题。

#include <string.h>
#include <stdio.h>
int main(void)
{
    char new_string[32] = "XXXXXXXXXXXXXXXX";
    char old_string[] = "string";
    memcpy(new_string, old_string, strlen(old_string) - 3);
    new_string[strlen(old_string) - 3] = '\0';
    printf("<<%s>> <<%s>>\n", old_string, new_string);
    return(0);
}

输出:

<<string>> <<str>>

然而,要注意棘手的巧合;我选择了一个长6个字符的样本旧字符串,-3给出'长度-3'也等于3。要获取最后N个字符,您需要更多代码:

#include <assert.h>
#include <string.h>
#include <stdio.h>

int main(void)
{
    int  N = 3;
    char new_string[32] = "XXXXXXXXXXXXXXXX";
    char old_string[] = "dandelion";
    int  sublen = strlen(old_string) - N;

    assert(sublen > 0);
    memcpy(new_string, old_string + sublen, N);
    new_string[N] = '\0';
    printf("<<%s>> <<%s>>\n", old_string, new_string);
    return(0);
}

输出:

<<dandelion>> <<ion>>

注意,编写像这样的小程序是很好的做法,并且可以是教育性的。编写大量代码是更好地编写代码的一种方法。

唯一需要注意的陷阱是,如果您正在测试“未定义的行为”,您只需从单个编译器获得响应,但其他编译器可能会生成行为不同的代码。这段代码没有运用未定义的行为,所以没关系。识别未定义的行为很棘手,因此您可以部分忽略此注释,但请确保使用编译器上的严格警告选项进行编译,这些选项可以帮助您识别未定义的行为。

我在一个名为vignettes的目录中提供了一些示例程序(在源代码管理下);如果我认为将来可能会再次需要它,那么它们就是一些程序,它们可以说明我可以参考的技术。他们是完整的;他们工作; (它们比这些具体的例子更复杂,但是我用C编程的时间比你更长;)但它们是玩具 - 有用的玩具。

答案 3 :(得分:2)

不,你必须使用这样的strlen()来获取最后的字符。

substr(strlen(str)-4,3);

记住字符串是基于0的,所以这给你最后3个。

所以一般技术是

substr(strlen(str)-n-1,n);

(当然字符串必须长于n

如果你想获得最后3个使用它:

substr(0,strlen(str)-4);

或者一般

substr(0,strlen(str)-n-1);

答案 4 :(得分:0)

我注意到substr不是标准的C函数,因此无法在C中使用它。因此,要通过消除最后几个字符来查找子字符串,可以使用memcpy(new_string, old_string, strlen(old_string) - 3)