【问题标题】:Using strtok to replace parts of a string from input file C使用 strtok 替换输入文件 C 中的部分字符串
【发布时间】:2015-10-24 16:01:50
【问题描述】:

所以我有一个简单的“猫狗鸡老鼠”文件。我正在尝试将其加载到字符串中并更改其中一个单词。我有

int main(){

    FILE *ifp;
    char *entry;
    char *string;
    char *token;

    ifp=fopen("/home/names.txt", "r");

    entry=malloc(200*sizeof(char));
    while(fgets(entry,75,ifp)){ 
    }

    printf("%s\n",entry);
    token=strtok(entry," ");

    while(token!=NULL){

        if(token=="dog")
            string="bird";

        string=token;
        printf("%s ",string);
        token=strtok(NULL," "); 
    }   
}

但是,当我尝试此操作时,它不会将“狗”一词替换为“鸟”。我做错了什么?

【问题讨论】:

  • 要在文件中替换吗?
  • 不,只是在我正在加载的字符串中
  • 1) while(fgets(entry,75,ifp)){ } 2) token=="dog" 3) string=token; 4) 省略
  • while(fgets(entry,75,ifp)){ } 仅获取文件的最后一行。为什么是 75 而不是 200?

标签: c string strtok


【解决方案1】:

现在这将修改原始字符串并将其存储在不同的字符数组中 -

char string[100];                // in your original code allocate memory to pointer string
token=strtok(entry," ");
size_t n;
while(token!=NULL){
  n=strlen(string);                      // calculate string length 
  if(strcmp(token,"dog")==0)             // if "dog" found
     sprintf(&string[n],"bird ");        // add "bird " at that position
  else
     sprintf(&string[n],"%s ",token);    //if doesn't add token 
  token=strtok(NULL," ");
}

注意 - 不要像这样比较字符串 -

    if(token=="dog")

使用来自<string.h> 的函数strcmp

【讨论】:

  • 所以这有助于我打印出替换的单词。但是,如果我想将整个内容存储到另一个字符串中呢?
  • @sam 我已经更新了代码。它将更新原始字符串。请看一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多