定义函数, 实现字符串中某个字符的查找, 并返回字符的下标或 -1

This commit is contained in:
flykhan 2023-06-25 16:59:08 +08:00
parent 782d75d3b1
commit ce1d2ae68f
1 changed files with 26 additions and 0 deletions

26
day9/case5.cpp Normal file
View File

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