【问题标题】:Pointer to string management in C: Replacing specific characters in a stringC 中指向字符串管理的指针:替换字符串中的特定字符
【发布时间】:2019-01-23 03:19:24
【问题描述】:

我想用“,-1”替换 .csv 文件中一行中的所有“,”。在这个id之前还想在行尾加逗号。

我试图通过将行分成两个子字符串来获得它.

此外,在此操作之前,我想在文件末尾添加一个额外的逗号,因此如果末尾有缺失值,也会得到处理。

//Get line from file
char line[70];
fgets(line, 70, infile);

//Add "," to the end of the line
char * temp;
temp = strstr(line, "/n");
strncpy(temp, ",/n", 2);
puts(line);

//Process Line
while (strstr(line, ",,") != NULL) {
    char * temp; 
    char endTemp[50];
    temp = strstr(line, ",,");
    strcpy(endTemp, temp + 2);
    strncpy(temp, ",-1,", 4);
    strcat(temp, endTemp);
    puts(line);
}

我认为我把两个子字符串弄乱了,因为如果起始字符串是这样的:

ajd43,232,,0,0,0,3

打印出来

ajd43,232,-1,0,0,0,3 ,(/n)0,0,0,3

我认为错误出现在最后的 strcat 中,但如果它们是执行此操作的更简单方法,我想使用它。

【问题讨论】:

    标签: c string string.h


    【解决方案1】:

    (1) 你的“/n”应该是“\n”。

    (2) 使用 strncpy(temp, ",\n", 3);或在 temp[2] 之后手动添加一个空字符。

    (3) 使用 strncpy(temp, ",-1,", 5);或者在 temp[4] 之后手动添加一个空字符。

    (4) 考虑截断并使用 strcat 而不是 strncpy。

    (5) 如果要在生产中使用,请检查是否溢出。

    (6) 只需用逗号替换换行符。 puts() 会将其添加回来。 (因此改变#2)

    像这样:

    // Get line from file
    char line[70];
    fgets(line, 70, infile);
    
    //Add "," to the end of the line
    char * temp;
    temp = strstr(line, "\n");
    strcpy(temp, ",");
    
    //Process Line
    while (strstr(line, ",,") != NULL) {
        char * temp; 
        char endTemp[70];
        temp = strstr(line, ",,");
        strcpy(endTemp, temp + 2);
        temp[0] = '\0';
        strncat(line, ",-1,", 70);
        strncat(line, endTemp, 70);
    }
    puts(line);
    

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 2013-02-16
      • 2021-06-21
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      相关资源
      最近更新 更多