用C++语言输入N个字符串,把其中以字母A打头的字符串输出。
时间: 2024-02-24 11:57:42 浏览: 25
可以使用字符串的substr函数来实现:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str[n];
for (int i = 0; i < n; i++) {
cin >> str[i];
}
for (int i = 0; i < n; i++) {
if (str[i].substr(0, 1) == "A") {
cout << str[i] << endl;
}
}
return 0;
}
```
该程序先读入N个字符串,然后使用for循环遍历每个字符串,使用substr函数取出字符串的第一个字符,如果第一个字符是"A",则将该字符串输出。substr函数的第一个参数是起始下标,第二个参数是子串长度,这里使用了1作为子串长度,表示取出第一个字符。最后将以字母A打头的字符串依次输出即可。
需要注意的是,由于输入字符串数量N是变量,因此需要使用动态数组来存储输入的字符串,这里使用了C++中的变长数组来实现。
相关问题
以void fun(char s[], int a[])开头设计C++:键盘输入一个字符串,统计其中的大写字母、小写字母、数字字母、其他字符的个数
下面是一个实现上述功能的C++代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void fun(char s[], int a[]) {
int len = strlen(s);
for (int i = 0; i < len; i++) {
if (s[i] >= 'A' && s[i] <= 'Z') {
a[0]++;
} else if (s[i] >= 'a' && s[i] <= 'z') {
a[1]++;
} else if (s[i] >= '0' && s[i] <= '9') {
a[2]++;
} else {
a[3]++;
}
}
}
int main() {
char s[100];
int a[4] = {0};
cout << "请输入一个字符串:";
cin >> s;
fun(s, a);
cout << "大写字母个数:" << a[0] << endl;
cout << "小写字母个数:" << a[1] << endl;
cout << "数字字符个数:" << a[2] << endl;
cout << "其他字符个数:" << a[3] << endl;
return 0;
}
```
其中,`fun`函数接受一个字符串和一个长度为4的整型数组作为参数,分别表示大写字母、小写字母、数字字母、其他字符的个数。函数中使用循环遍历字符串中的每个字符,根据其ASCII码值判断其属于哪类字符,然后相应的计数器加1。最后在`main`函数中,先输入一个字符串,再调用`fun`函数统计各类字符的个数,最后输出结果。
c++ 判断一个字符串是不是o开头的
可以使用字符串的`substr()`函数和比较运算符来判断一个字符串是否以字母 'o' 开头。
```cpp
#include <iostream>
#include <string>
bool startsWithO(const std::string& str) {
if (str.length() > 0 && str[0] == 'o') {
return true;
}
return false;
}
int main() {
std::string testStr1 = "open";
std::string testStr2 = "close";
if (startsWithO(testStr1)) {
std::cout << testStr1 << " starts with 'o'" << std::endl;
} else {
std::cout << testStr1 << " does not start with 'o'" << std::endl;
}
if (startsWithO(testStr2)) {
std::cout << testStr2 << " starts with 'o'" << std::endl;
} else {
std::cout << testStr2 << " does not start with 'o'" << std::endl;
}
return 0;
}
```
输出结果为:
```
open starts with 'o'
close does not start with 'o'
```
在`startsWithO()`函数中,使用`substr(0, 1)`提取字符串的第一个字符,并与字母 'o' 进行比较。如果相等,则返回`true`,否则返回`false`。在`main()`函数中,调用`startsWithO()`函数并根据返回值输出相应的结果。