[英]Removing a comma from an array
我正在尝试制作一个从数组中删除逗号并具有以下 output 的程序:
sub hi.txt
sub hello.txt
sub hey.txt
sub yo.txt
sub whatsup.txt
我的代码是:
int main(void)
{
int aux=0;
int aux2=0;
char sub[100];
char f [] = "hi.txt,hello.txt,hey.txt,yo.txt,whatsup.txt";
size_t n = (int)sizeof(f) / sizeof(f[0]);
for (int i = 0; i < n ;i++)
{
if(f[i] == '.')
{
for(int c=aux; c<i+4;c++)
{
sub[aux2] = f[aux];
aux++;
aux2++;
}
aux=i+5;
aux2=0;
printf("sub %s\n",sub);
sub[0]='\0';
}
}
return 0;
}
然而,即将到来的结果是:
sub hi.txt
sub hello.txt
sub hey.txtxt
sub yo.txttxt
sub whatsup.txt
您不是 null 终止您的 substring。 添加sub[aux2] = '\0';
在设置aux2 = 0
之前
顺便说一句,您会发现使用string.h
function strlen
更容易获得字符串长度
size_t n = strlen(f);
虽然手动循环很好(您可能会发现使用开始和结束指针比索引更容易),但 C 已经提供了可以在一组分隔符( strtok
和strsep
)上标记字符串的函数。 在您的情况下,您可以使用strtok
将f
中包含的字符串简单地分成单独的子字符串,例如
#include <stdio.h>
#include <string.h>
int main (void) {
char f[] = "hi.txt,hello.txt,hey.txt,yo.txt,whatsup.txt";
/* tokenize f on , */
for (char *p = strtok (f, ","); p; p = strtok (NULL, ","))
printf ("sub %s\n\n", p);
}
(注意: strtok
通过插入'\0'
代替分隔符来修改原始字符串,因此如果您需要保留原始字符串,则需要制作副本。)
示例使用/输出
$ ./bin/splitoncomma
sub hi.txt
sub hello.txt
sub hey.txt
sub yo.txt
sub whatsup.txt
提供的可以使用的附加函数是strcspn
和strspn
(可以在不修改原始字符串的情况下结合使用),或者对于您拥有的单字符分隔符, strchr
或一对指针也可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.