首页 > 解决方案 > 交换文件内的字符

问题描述

  FILE* f;  /// pointer to a File structure
  char cuv[100];
  int i;
  f = fopen("exmp.txt", "a+");  /// open the file and add the registry. the end
  puts("enter words to add to file");
  for (i = 1; i <= 3; i++) {
    gets(cuv);  /// enters the character string
    fprintf(f, "% s", cuv);
  }  /// write
  puts("File contents:");
  rewind(f);               /// goes to the beginning of the file
  fscanf(f, "% s", &cuv);  /// read
  puts(cuv);               /// displaying the string on the screen by adding \ n
  getch();
  fclose(f);
}  /// close the file

我有这个程序可以在文件末尾添加单词,它可以正常工作,但我希望它可以将字母 a 与字母 b 交换,反之亦然

我发现了一段代码可以满足我的要求,但我似乎无法让它工作。如果我更改某些内容,它只会破坏代码

for (int a = 0; a < strlen(cuv); a++){
  if (cuv[a] == 'a'){
    cuv[a] = m;
  } else if(cuv[a] == 'b'){
    cuv[a] = c;
  }
}

有没有更简单的方法来交换 2 个字符?

标签: c

解决方案


  1. 把这两个变成函数。

  2. 对于第二个,在你的函数中试试这个。我假设 nom 是您想要交换“a”和“b”的词。

# nome must be defined prior to this
for (int a = 0; a < strlen(nome); a++){
  if (nome[a] == 'a'){
    nome[a] = 'b';
  } else if(nome[a] == 'b'){
    nome[a] = 'a';
  }
}
# nome must be returned at this point

就个人而言,我会为此目的选择除“a”之外的任何其他索引变量名称。


推荐阅读