[英]How to solve this task? Find substring in string. C language
我必須編寫一個程序,從用戶那里檢索僅包含字母“A”和“B”的字符串。 該字符串長度為 10 個字符(每個字符必須單獨讀取)。 當程序發現該字符串中存在序列“ABBA”時,它應該檢測並發出信號。
沒有數組怎么辦? 我認為唯一的方法是制作 10 scanf 和許多 IF 語句。
您可以有 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.