程序设计:输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有,则输出1
时间: 2024-05-16 11:17:29 浏览: 21
下面是Python的实现代码:
```python
s = input("请输入一个字符串:")
c = input("请输入一个字符:")
if c in s:
print("字符在字符串中首次出现的位置为:", s.index(c))
else:
print("字符在字符串中未出现,输出1")
```
代码实现很简单,首先输入一个字符串和一个字符,然后用 `in` 判断字符是否在字符串中出现过,如果出现过,使用 `index` 方法查找其在字符串中首次出现的位置并输出;如果未出现,则直接输出1。
相关问题
C++程序设计输入一个字符串和一个字符,查找并输出字符在字符串中首次出现的位置,如果没有则输出-1
下面是一个用 C++ 实现的例子:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str);
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch);
if (pos == string::npos) {
cout << "-1" << endl;
} else {
cout << pos << endl;
}
return 0;
}
```
运行程序后,会提示用户输入一个字符串和一个字符,然后查找并输出字符在字符串中首次出现的位置。如果没有找到该字符,则输出-1。例如,输入字符串 "hello world" 和字符 'w',则输出结果为 6。如果输入字符串 "hello world" 和字符 'z',则输出结果为 -1。
C + +输入一个字符串和一个字符查找并输出字符在字符串中首次出现的位置如果没有则输出-1
下面是 C++ 代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
char ch;
cout << "请输入一个字符串:";
getline(cin, str); // 使用 getline() 函数读取一行字符串,避免空格被忽略
cout << "请输入一个字符:";
cin >> ch;
int pos = str.find(ch); // 在字符串中查找字符
if (pos == string::npos) {
cout << "没有找到该字符!" << endl;
} else {
cout << "该字符在字符串中第一次出现的位置为:" << pos << endl;
}
return 0;
}
```
运行程序后,输入一个字符串和一个字符,即可输出字符在字符串中首次出现的位置。如果没有找到该字符,则输出 `-1`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)