改成c语言并且能在vs2022运行#include <iostream> #include <string> using namespace std; int patternMatch(string str, string pattern) { int n = str.size(); int m = pattern.size(); if (n < m) { return -1; // 如果文本串长度小于模式串,匹配失败 } for (int i = 0; i <= n - m; i++) { bool isMatched = true; for (int j = 0; j < m; j++) { if (str[i + j] != pattern[j]) { isMatched = false; break; } } if (isMatched) { return i; // 返回匹配成功的起始位置 } } return -1; // 匹配失败 } int main() { string str = "hello world"; string pattern = "world"; int pos = patternMatch(str, pattern); if (pos != -1) { cout << "匹配成功,起始位置为:" << pos << endl; } else { cout << "匹配失败!" << endl; } return 0; }
时间: 2024-02-14 13:14:44 浏览: 50
使用include <iostream>时一定要加using namespace std
以下是改成C语言并且能在VS2022运行的代码:
```c
#include <stdio.h>
#include <string.h>
int patternMatch(char* str, char* pattern) {
int n = strlen(str);
int m = strlen(pattern);
if (n < m) {
return -1; // 如果文本串长度小于模式串,匹配失败
}
for (int i = 0; i <= n - m; i++) {
int isMatched = 1;
for (int j = 0; j < m; j++) {
if (str[i + j] != pattern[j]) {
isMatched = 0;
break;
}
}
if (isMatched) {
return i; // 返回匹配成功的起始位置
}
}
return -1; // 匹配失败
}
int main() {
char str[] = "hello world";
char pattern[] = "world";
int pos = patternMatch(str, pattern);
if (pos != -1) {
printf("匹配成功,起始位置为:%d\n", pos);
} else {
printf("匹配失败!\n");
}
return 0;
}
```
阅读全文