区分大小写==输入数据全部转化为大写或者小写
这种一部分不对,就不能简单的遍历用find函数
-
接收数据
- cin函数碰到空格,制表符,换行会停止,不会读入\n
- getline函数只有在换行符才会停止,并且会读入\n
- 有时候读入错了看看是不是没有忽略换行cin.ignore();
-
处理数据,转化为小写
-
遍历essay,来统计里面的字符个数
tips:当使用分隔符来处理字符串的时候,我们要注意第一个和最后一个单词需要特殊处理,如果我们不想特殊处理,可以在句子的前后都加上分隔符
加上分隔符
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
//正确的获取输入
string word,essay;
getline(cin,word);
getline(cin,essay);
//转换大小写
for(int i=0;i<word.length();i++){
if(word[i]>='A'&&word[i]<='Z'){
word[i]=word[i]+32;
}
}
for(int i=0;i<essay.length();i++){
if(essay[i]>='A'&&essay[i]<='Z'){
essay[i]=essay[i]+32;
}
}
//字符串的首单词和末尾单词需要特殊处理,为了避免这种特殊处理,我们可以将字符串的最后和前面都加上分隔符
essay =" "+essay+" ";
int cnt=0;
//注意这里必须是单词to,而不是某个单词中含有to,所以直接在整个字符串中查找是不正确的
string temp="";
int first=-1;
for(int i=0;i<essay.length();i++){
if(essay[i]!=' '){
temp+=essay[i];
}else{
if(temp==word){
cnt++;
if(cnt==1){
//因为加了空格
first =i-temp.length()-1;
}
}
temp="";
}
}
if(first!=-1){
cout<<cnt<<" "<<first;
}else{
cout<<-1;
}
return 0;
}
特殊处理
#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
//正确的获取输入
string word,essay;
getline(cin,word);
getline(cin,essay);
//转换大小写
for(int i=0;i<word.length();i++){
if(word[i]>='A'&&word[i]<='Z'){
word[i]=word[i]+32;
}
}
for(int i=0;i<essay.length();i++){
if(essay[i]>='A'&&essay[i]<='Z'){
essay[i]=essay[i]+32;
}
}
//字符串的首单词和末尾单词需要特殊处理,为了避免这种特殊处理,我们可以将字符串的最后和前面都加上分隔符
int cnt=0;
//注意这里必须是单词to,而不是某个单词中含有to,所以直接在整个字符串中查找是不正确的
string temp="";
int first=-1;
for(int i=0;i<essay.length();i++){
if(i==essay.length()-1){
if(temp==word){
cnt++;
if(cnt==1){
first =i-temp.length();
}
break;
}
}
if(essay[i]!=' '){
temp+=essay[i];
}else{
if(temp==word){
cnt++;
if(cnt==1){
first =i-temp.length();
}
}
temp="";
}
}
if(first!=-1){
cout<<cnt<<" "<<first;
}else{
cout<<-1;
}
return 0;
}
附带find函数的使用
#include<iostream>
#include<string>
using namespace std;
int main(){
string word="word",essay="wwords";
//参数.find(模式串) 参数是从这里查找
//原本的返回值是size_t
int result = essay.find(word);//如果用int值来接受那结果就是-1
result = essay.find(word,1);//从下标为1的地方开始查找,包括下标为1的这个字符
if(result!=essay.npos){//result!=essay.npos
printf("查找成功,下标是%d",result);
}else{
printf("查找失败,下标是%d",result);
}
}
大小写转换
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "hello world";
//transform(str.begin(), str.end(), str.begin(),::tolower);
transform(str.begin(), str.end(), str.begin(),::toupper);
cout << str << std::endl;
return 0;
}