Text Editor

 avatar
unknown
c_cpp
2 years ago
1.9 kB
6
Indexable
#include <stdio.h>
#include <string.h>

#define MAX_SIZE 500

char content[MAX_SIZE];
char input[MAX_SIZE];
char tmp[MAX_SIZE];
char com[4][30] = {"/backspace", "/newline", "/left", "/right"};
int ans_index = 0;

void shift(){
    int l = strlen(content);
    for(int i = l; i > ans_index; i--){
        content[i] = content[i-1];
    }
    return;
}

int check(){
    for(int i = 0; i < 4; i++){
        if(strcmp(tmp, com[i]) == 0){
            if(i == 0 && ans_index > 0){
                ans_index--;
                int l = strlen(content);
                for(int j = ans_index; j < l; j++){
                    content[j] = content[j+1];//注意變數不要寫成i
                }
            }
            else if(i == 1){
                if(content[ans_index] != '\0') shift();
                content[ans_index] = '\n';
                ans_index++;
            }
            else if(i == 2 && ans_index > 0) ans_index--;
            else if(i == 3 && ans_index < strlen(content)) ans_index++;
            return 1;
        }
    }
    return 0;
}

int main(){

    fgets(input, MAX_SIZE, stdin);
    memset(content, '\0', MAX_SIZE);
    memset(tmp, '\0', MAX_SIZE);

    int len = strlen(input);
    int mode = 0, index = 0;

    for(int i = 0; i < len; i++){
        if(input[i] == '/') mode = 1;
        if(mode == 0 && input[i] != '\n'){
            if(content[ans_index] != '\0'){
                shift();
            }
            content[ans_index] = input[i];
            ans_index++;
        }
        else if(mode == 1){
            tmp[index] = input[i];
            index++;
            if(check() == 1){
                mode = 0, index = 0;
                memset(tmp, '\0', sizeof(tmp));
            }
        }
    }

    printf("%s", content);

    return 0;
}
Editor is loading...