简体   繁体   English

如何解决这个任务? 在字符串中查找子字符串。 C语言

[英]How to solve this task? Find substring in string. C language

I must write a program that will retrieve from the user the string consisting only letters "A" and "B".我必须编写一个程序,从用户那里检索仅包含字母“A”和“B”的字符串。 That string length is 10 characters (each character must be read separately).该字符串长度为 10 个字符(每个字符必须单独读取)。 The program should detect and signal when it finds the sequence "ABBA" is in that string.当程序发现该字符串中存在序列“ABBA”时,它应该检测并发出信号。

How to do it without arrays?没有数组怎么办? I think the only way to do it, is make 10 scanf, and many of IF statements.我认为唯一的方法是制作 10 scanf 和许多 IF 语句。

You can have 4 states: state 0 is looking for the first A, state 1 is looking for the first B, state 2 is looking for the second B, and state 3 is looking for the second A:您可以有 4 个状态:状态 0 正在寻找第一个 A,状态 1 正在寻找第一个 B,状态 2 正在寻找第二个 B,状态 3 正在寻找第二个 A:

int state = 0;
for (int i = 0; i < 10; i ++) {
    char c = getchar();
    if (c == 'A' && (state == 0 || state == 3)) {
        // found match, advance
        state ++;
        continue;
    }
    if (c == 'B' && (state == 1 || state == 2)) {
        // found match, advance
        state ++;
        continue;
    }
    if (state == 4) {
        // finished, we can break
        break;
    }
    // no match, reset
    state = 0;
}
if (state == 4) {
    puts("substring found");
} else {
    puts("substring not found");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM