2023-06-25 16:59:08 +08:00
|
|
|
// 定义函数, 实现字符串中某个字符的查找, 并返回字符的下标或 -1
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
int findCharAt(char str[], int size, char ch)
|
|
|
|
{
|
|
|
|
for (int i = 0; i < size; i++)
|
|
|
|
{
|
|
|
|
if (str[i] == ch)
|
|
|
|
return i;
|
|
|
|
else if (str[i] == '\0' && str[i] != ch)
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
2023-06-26 08:34:05 +08:00
|
|
|
// char str[] = "abcdefg";
|
|
|
|
char str[128];
|
|
|
|
cout << "请输入字符串: ";
|
|
|
|
cin >> str;
|
2023-06-25 16:59:08 +08:00
|
|
|
char ch;
|
|
|
|
cout << "请输入要查找的字符: ";
|
|
|
|
cin >> ch;
|
|
|
|
int size = sizeof(str) / sizeof(str[0]);
|
|
|
|
int index = findCharAt(str, size, ch);
|
|
|
|
cout << "下标为: " << index << endl;
|
|
|
|
return 0;
|
|
|
|
}
|