gpt4 book ai didi

c - 在某个重复字符后从字符串中删除文本

转载 作者:行者123 更新时间:2023-12-05 06:58:47 25 4
gpt4 key购买 nike

char str[] = "C:\\Users\\test\\Desktop\\folder\\test.txt";
char *ptr;

ptr = strchr(str, '\\');
if (ptr != NULL) {
*ptr = '\0';
}

如何删除包括 test.txt 在内的最后一个“\”,使其只是“C:\Users\test\Desktop\folder”

谢谢

最佳答案

你想要strrchr

Locate last occurrence of character in stringReturns a pointer to the last occurrence of character in the Cstring str.

The terminating null-character is considered part of the C string.Therefore, it can also be located to retrieve a pointer to the end ofa string.

您还需要使用 \\ 转义反斜杠:

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

int main(void)
{
char str[] = "C:\\Users\\test\\Desktop\\folder\\test.txt";
char *ptr;

ptr = strrchr(str, '\\');
if (ptr != NULL) {
*ptr = '\0';
}
puts(str);
}

关于c - 在某个重复字符后从字符串中删除文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64540713/

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