c - TAG 替换 C 字符串

标签 c string

希望您能给我一些启发:

有此条目:

BODY
10
<><BODY garbage>body</BODY>

所以我必须替换 <> 中的所有标签并使输出如下所示:

<><10 garbage>body</10>

有什么想法吗? 谢谢!

最佳答案

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

int main (void){
    char tag[128];//enough?
    char tag_r[128];
    char text[1024] = "";//enough? or dynamic array like as vector
    int text_pos = 0;
    int ch;
    enum { OUT, IN };
    int status = OUT;

    scanf("%127s %127[^\n]%*c", tag, tag_r);
    while((ch = getchar())!=EOF){
        if(status == OUT){
            putchar(ch);
            if(ch == '<')
                status = IN;
        } else {//if(status == IN){
            if(ch == '>'){
                size_t len = strcspn(text, " \t\n");
                if(len && strncmp(text, tag, len)==0){//match start tag(insufficient rigor), ignore case?
                    printf("%s", tag_r);
                    printf("%s", text + len);
                } else if(text[0]=='/' && strcmp(text+1, tag)==0){//match end tag
                    printf("/%s", tag_r);
                } else {
                    printf("%s", text);
                }
                text[text_pos=0]=0;
                putchar(ch);
                status = OUT;
            } else {
                text[text_pos++] = ch;//check omitted
                text[text_pos] = 0;
            }
        }
    }
    if(text_pos)//invalid syntax
        printf("%s", text);
    return 0;
}

关于c - TAG 替换 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199887/

相关文章:

c - 使用按位运算符进行快速字符串搜索

java - 输入一长串数字时不断出现错误

c++ - 调试断言失败缓冲区!= NULL

python - 如何在python中用一个单词替换多个单词?

javascript - 从 URL 中删除最后两个参数

c - 基础问题 : Best Practices concerning Posix Threads and Dynamic Memory

c - 如何将字符串类型转换为具有不同大小的 char 数组成员的结构?

c - 扫描二维字符数组

c++ - cvNorm() 使用的默认范数类型是什么?

python - 使用pyserial向Arduino发送信息(操作步进电机)