|
发表于 2023-10-12 15:35:02
|
显示全部楼层
这道题目的问题在于第二个for循环中的语句块没有被正确的限定在if语句中,导致每次循环都会执行一遍,从而计数器t的值被重复累加。正确的代码应该是这样的:
- #include <bits/stdc++.h>
- using namespace std;
- int main()
- {
- int n,t=0;
- string s;
- cin>>n;
- for(int i=0;i<n;i++)
- {
- cin>>s;
- for(int j=0;j<s.size();j++) // 遍历字符串s
- {
- s[j]=tolower(s[j]); // 将字符转为小写
- }
- if(s.find("alan")!=-1) // 判断字符串是否包含"alan"
- {
- t++;
- }
- }
- cout<<t<<endl;
- }
复制代码
关于find函数的用法,它的语法是这样的: s.find(str, pos) ,其中 s 是一个字符串, str 是要查找的子字符串, pos 是查找的起始位置。如果找到了子字符串,返回它在 s 中的起始位置,否则返回 string::npos 。在这道题目中,我们用 if(s.find("alan")!=-1) 来判断字符串 s 中是否包含"alan",如果包含,计数器 t 就加1。在这里, find 函数返回的是子字符串在 s 中的起始位置,如果返回的是 string::npos ,说明没找到,它的值为-1。因此,我们用 if(s.find("alan")!=-1) 来判断是否找到了"alan"。如果找到了,就执行 t++ ,计数器 t 就加1。如果没找到,就不执行 t++ ,计数器 t 保持不变。
至于为什么 t=s.find("bob") 时,输出的 t 值为0,这是因为 find 函数返回的是子字符串在 s 中的起始位置,如果子字符串是 s 的第一个字符,它的起始位置就是0。 |
|