qfedu-basic-level/day9/case5.cpp

29 lines
684 B
C++

// 定义函数, 实现字符串中某个字符的查找, 并返回字符的下标或 -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()
{
// char str[] = "abcdefg";
char str[128];
cout << "请输入字符串: ";
cin >> str;
char ch;
cout << "请输入要查找的字符: ";
cin >> ch;
int size = sizeof(str) / sizeof(str[0]);
int index = findCharAt(str, size, ch);
cout << "下标为: " << index << endl;
return 0;
}