定义函数, 实现字符串中某个字符的查找, 并返回字符的下标或 -1
This commit is contained in:
parent
782d75d3b1
commit
ce1d2ae68f
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue