c语言中如何除掉最后一个逗号
时间: 2023-05-24 15:03:13 浏览: 1763
在C语言中,如果想要除掉最后一个逗号,可以使用以下方法:
1. 手动去除逗号:在编写代码时,在最后一个逗号处手动删除逗号。
2. 使用字符串处理函数strncpy()和strlen():将字符串复制到新的数组中,并在最后一个逗号位置上添加字符串结束符'\0'。代码示例如下:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "1,2,3,4,5,";
int len = strlen(str1);
char str2[len];
strncpy(str2, str1, len-1); // 复制字符串到新的数组中
str2[len-1] = '\0'; // 在最后一个逗号位置上添加字符串结束符
printf("原字符串:%s\n", str1);
printf("新字符串:%s\n", str2);
return 0;
}
```
运行结果如下:
```
原字符串:1,2,3,4,5,
新字符串:1,2,3,4,5
```
3. 使用正则表达式:使用正则表达式匹配最后一个逗号并去除。代码示例如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
int main()
{
char str1[] = "1,2,3,4,5,";
char *pattern = ",$"; // 匹配最后一个逗号
char *replace = ""; // 替换为空字符串
regex_t reg;
regmatch_t pmatch[1];
if(regcomp(®, pattern, REG_EXTENDED | REG_NEWLINE) != 0) {
perror("regcomp error");
exit(1);
}
if(regexec(®, str1, 1, pmatch, 0) == 0) {
char *str2;
str2 = (char *)malloc((pmatch[0].rm_so+1) * sizeof(char)); // 新字符串的长度为匹配到的位置+1
strncpy(str2, str1, pmatch[0].rm_so);
str2[pmatch[0].rm_so] = '\0';
strcat(str2, replace); // 将替换字符串添加到新字符串中
printf("原字符串:%s\n", str1);
printf("新字符串:%s\n", str2);
}
regfree(®);
return 0;
}
```
运行结果如下:
```
原字符串:1,2,3,4,5,
新字符串:1,2,3,4,5
```