我有一个类似于下面的字符串-并希望在字符串中的每个逗号后添加双引号。
我试图用“,\”“替换,但是没有用。
//orginal strign
char *mystring = "test,blabla,blabla,blabla";
//want to convert this format, after adding double quote
char *newstring = " test,\"blabla,\"blabbla,\"blabla";
如何用C编程语言在字符串中的每个逗号后面加上双引号?
答案 0 :(得分:2)
如果我很了解您想要这样的话:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *mystring = "test,blabla,blabla,blabla";
int n = 0;
const char * p1;
/* compute result length */
for (p1 = mystring; *p1; ++p1)
n += (*p1 == ',') ? 2 : 1;
/* make result string */
char * r = malloc(n + 1);
char * p2 = r;
for (p1 = mystring; *p1; ++p1) {
if ((*p2++ = *p1) == ',')
*p2++ = '"';
}
*p2 = 0;
/* show it works */
printf("%s\n", r);
return 0;
}
显示test,"blabla,"blabla,"blabla
如果您想在备注中也将\放在前面,
#include <stdio.h>
#include <stdlib.h>
int main()
{
const char *mystring = "test,blabla,blabla,blabla";
int n = 0;
const char * p1;
/* compute result length */
for (p1 = mystring; *p1; ++p1)
n += (*p1 == ',') ? 3 : 1;
/* make result string */
char * r = malloc(n + 1);
char * p2 = r;
for (p1 = mystring; *p1; ++p1) {
if ((*p2++ = *p1) == ',') {
p2[0] = '\\';
p2[1] = '"';
p2 += 2;
}
}
*p2 = 0;
/* show it works */
printf("%s\n", r);
return 0;
}
显示:test,\"blabla,\"blabla,\"blabla