c - 用C中的空格替换字符数组中的制表符

标签 c arrays file-io

我做了一个小的 C 程序,这样我就可以自动清除作业中的所有制表符,并用 4 个空格替换它们。我在具有以下功能的字符数组中找到选项卡 -

char * tabFinder(char * fileString,int * nonNullItems)
{
    int numElements = 0;
    int run = 1;
    while(run)
    {
        while(fileString[numElements] != '\t' &&
              fileString[numElements] != '\0')
            numElements++;

        if(fileString[numElements] == '\t')
        {
            fileString = tabDestroyer(fileString,&numElements,nonNullItems);
            *nonNullItems = *nonNullItems + 3;
        } else run = 0;

    }
    fileString[*nonNullItems + 1] = '\0';
    return fileString;
}

每次找到一个选项卡时,它都会将它传递给我的替换函数 tabDestroyer,它看起来像这样 -

char * tabDestroyer(char * fileString, int * indexOfTab,int * currentItems)
{
    char * tempString = malloc(*currentItems + 3);
    int index = 0,tempIndex;;

    while(index < *indexOfTab)
    {
        tempString[index] = fileString[index];
        index++;
    }   

    tempString[index++] = " ";

    tempString[index++] = " ";

    tempString[index++] = " ";

    tempString[index++] = " ";


    *currentItems = *currentItems + 3;

    while(index < *currentItems)
    {
        tempString[index] = fileString[index - 3];
        index++;
    }

    return tempString;
}

它成功找到并替换了选项卡,但我对替换选项卡的内容有疑问。

例如,从文件中读入的字符串看起来像这样(假装前面有一个标签)-

        int i, numHuge, rowCount = 0;

变成这个-

FFFFint i, numHuge, rowCount = 0;

知道为什么会这样吗?

最佳答案

char * tempString;
tempString[index++] = " ";
                      ^ ^

对于初学者,使用单引号,即 ' '

关于c - 用C中的空格替换字符数组中的制表符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14222487/

相关文章:

c - 字符串的第一个字符在哪里?

bash - 如何使用 Bash 创建文件的副本,在扩展名前添加一个额外的后缀?

c - 成员之间不会有填充是否安全?

header 中的 C++ 数组

c - 对函数 'check' 的 undefined reference (MinGW 中的 GCC 编译)

java - 动态字符串数组java

java - 使用 iText java 选择整个 pdf 文档的文本和背景

c - 关于文件 I/O(读/写消息字符串)的很多问题

c - 在 C 中使用带有 for 循环的数组

c++ - 这个归并排序有问题