簡體   English   中英

更改字符串中的字母

[英]change letters in strings

我正在做一個將字母“e”更改為“a”的項目,但我仍然完全不正確。 我的輸入是一個文件 abc.txt: '''

Im enne end
my ded is frenk
My mom is elycie Lou

''' 我的輸出是“我媽媽是 alycie Lou”,另一行是“我媽媽是 alicya Lou”。 繼承人我的代碼。 任何人都可以幫助我嗎?

'''

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 3
#define MAX_STRING_SIZE 50


int main()
{
   char line[MAX_LINE][MAX_STRING_SIZE];
   int i=0;
   FILE *arch;
   arch = fopen("abc.txt", "r");

   if (arch==NULL){
       printf("ERROR");
    }
    else{
        while (!feof(arch)){
            fgets(line[i], MAX_STRING_SIZE , arch);
            i++;
        }
    }
    fclose(arch);

    for ( i=0; line[i][MAX_STRING_SIZE]; ++i )
    {
        if ( line[i][MAX_STRING_SIZE] == 'e' )
        {
            line[i][MAX_STRING_SIZE] = 'a';

        }
    }printf("%s", line);

    return 0;
}

'''

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int i;
   char line[50];
   FILE *arch;
   arch = fopen("abc.txt", "r");

   if (arch==NULL){
       printf("ERROR");

更好: perror("abc.txt"); exit(EXIT_FAILURE); perror("abc.txt"); exit(EXIT_FAILURE);

    }
    else{
        while (!feof(arch)){

看到while(!feof()) 總是錯誤的

            fgets(line, 50 , arch);
            //store all strings from the file
        }

不! 這不會存儲文件中的所有字符串。 這將從文件中讀取所有字符串,並保留最后一個讀取的line 在您的情況下,當循環完成時(忽略來自while(!feof()) ), line將包含文件中的最后一行。

    }
    fclose(arch);

    for ( i=0; line[i]; ++i )
    {
        if ( line[i] == 'e' )
        {
            line[i] = 'a';
            printf("%s", line);

您想打印與'e'一樣多的行嗎? 如果您只想在所有'e'轉換后打印一次,請將printf行移動到for循環結束之后

        }
    }

    return 0;
}

玩得開心!

這里有一些我會考慮實施的提示

首先更改您的行聲明,並聲明一個不是i的計數器。 我們將同時使用icounter

char line[MAX_STRING_SIZE];
int counter = 0;

然后我會對讀取文件的 while 循環執行此操作。 請注意,如果counter等於或超過MAX_LINE則循環將退出:


while (((fgets(line, MAX_STRING_SIZE , arch)) != NULL) && counter < MAX_LINE)
{
    for ( i=0; line[i]; ++i )
    {
        if ( line[i] == 'e' )
        {
            line[i] = 'a';
        }
    }
    printf("%s", line);
    counter++;
}

嘗試這些,看看它是否會產生所需的行為。

希望能幫助到你!

當您想對整個文件的內容執行某些操作時(將所有'e' s 更改為'a' s,刪除所有出現的單詞"very" ,...),您應該考慮的第一件事是:我將逐行讀取文件,處理每一行,直到沒有更多行。 這個想法最直接的實現是

char line[MAX_LINE_LENGTH];
// use FILE *f = fopen(filename, "r"); instead of stdin
while (fgets(line, sizeof line, stdin)) {
    process(line);
}
// remember to fclose(f) if not using stdin

記住這 4(或 6)行; 你會經常使用它們。

在您的特定情況下(您想用'a' s 而不是'e' s 打印行) process()函數可能類似於:

void process(const char *line) {
    for (int i = 0; i < strlen(line); i++) {
        if (line[i] == 'e') putchar('a');
        else putchar(line[i]);
    }
}

就是這樣。 你的大部分程序都完成了。

添加正確的#include s、錯誤檢查、 main()並收工。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM