用C++写一个模拟strrstr函数的程序,不能用指针,若找到返回1-n,否则返回0
时间: 2023-06-13 07:09:18 浏览: 46
假设我们要在字符串 `str` 中查找字符串 `substr`,以下是一个不使用指针的 C++ 实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int findSubstring(char str[], char substr[]) {
int str_len = strlen(str);
int substr_len = strlen(substr);
if (substr_len > str_len) {
return 0;
}
for (int i = 0; i <= str_len - substr_len; i++) {
bool found = true;
for (int j = 0; j < substr_len; j++) {
if (str[i + j] != substr[j]) {
found = false;
break;
}
}
if (found) {
return i + 1;
}
}
return 0;
}
int main() {
char str[100], substr[100];
cout << "Enter the string: ";
cin.getline(str, 100);
cout << "Enter the substring to search for: ";
cin.getline(substr, 100);
int result = findSubstring(str, substr);
if (result) {
cout << "Substring found at position " << result << endl;
} else {
cout << "Substring not found" << endl;
}
return 0;
}
```
该程序中,我们首先比较了要查找的子字符串长度和原字符串长度,如果子字符串长度大于原字符串长度,那么就不可能找到子字符串,直接返回 0。然后,我们遍历原字符串中的每个字符,依次与子字符串中的字符进行比较,如果匹配成功则返回其起始位置(加 1 是为了符合题目要求),如果遍历完原字符串都没找到,则返回 0。