字符串
来源:互联网 发布:手机淘宝查号网址 编辑:程序博客网 时间:2024/06/05 19:58
一般类型:string;
比如 hello word! Interestring! Me 123 44 4 34 41 dmk(空格也算);
String 都可以用cin cout(输出文字也行);
例1:输入一个字符串,去掉空格输出
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,x;
cin>>s;
while(cin>>x)
{
s=s+' '+x;
}
cout<<s;
return 0;
}
字符串也能设数组 如:string s[1000]={每个数组的赋值};
Size是一个测字符串的函数,测字符串的长度,如:
S=‘abcdefghijklmnopqrstuvwxyz’;
Int l
L=s.size();
那么l=26;
例2:输入一个字符串,输出数字个数。
(getline是一个只会被回车影响的输入;如
A Getline(cin>>S)
Cout<<s;
B Cin>>>s;
Cout<<s;
输入 abcde abcde
A输出:abcde abcde
B 输出:abcde
)
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
int c=0;
for(int i=0;i<=s.size();i++)
{
if(s[i]>='0'&&s[i]<='9')c++;
}
cout<<c;
return 0;
}
取字符函数:()
例3:输入人的姓名,按字典序排序;
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;string a[n+1];
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
cout<<a[i]<<endl;
}
(Sort也可以字典序排序)
Swap用法
# include <iostream># include <string>using namespace std;int main()
{
string str1 ="yesterday once more";
string str2 ("my heart go on");
str2.swap(str1);
cout<<str1<<endl;// = my heart go on
cout<<str2<<endl;// = yesterday once more
getchar();
return 0;
}
20)查找函数
查找函数很多,功能也很强大,包括了:
find()
rfind()
find_first_of()
find_last_of()
find_first_not_of()
find_last_not_of()
这些函数返回符合搜索条件的字符区间内的第一个字符的索引,没找到目标就返回npos。所有的函数的参数说明如下:
第一个参数是被搜寻的对象。第二个参数(可有可无)指出string内的搜寻起点索引,第三个参数(可有可无)指出搜寻的字符个数。比较简单,不多说不理解的可以向我提出,我再仔细的解答。当然,更加强大的STL搜寻在后面会有提及。
最后再说说npos的含义,string::npos的类型是string::size_type,所以,一旦需要把一个索引与npos相比,这个索引值必须是string::size)type类型的,更多的情况下,我们可以直接把函数和npos进行比较(如:if(s.find(“jia”)== string::npos))。
# include <iostream>
# include <string>
using namespace std;int main()
{
string str ="when i was young, i listen to radio.";
string::size_type position;
position =str.find("listen");
if (position !=str.npos)//npos是个很大的数,如果没找到就会返回npos的值给position
{
cout<<"第一次出现的下标是:"<<position<<endl;
}
//从字符串下标9开始,查找字符串you,返回you 在str中的下标
position =str.find("you",9);
cout<<"str.find("you",9")is:"<<position<<endl;
//查找子串出现的所有位置
string substr = "i";
position = 0;
int i = 1;
while((position = str.find_first_of(substr,position)) != string::npos)
{
cout<<"position"<<i++<<position<<endl;
position++;
}
//反向查找子串在str中最后出现的位置
string flag = "to";
position = str.rfind(flag);
cout<<"str.rfind(flag):"<<position<<endl;
getchar();
return 0;
}
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 字符串
- 数据结构实验之图论五:从起始点到目标点的最短步数(BFS)
- Spring的事物管理之数据并发引发的问题
- vs2017下搭建gtest LLT环境
- 云主机的「集中」还是「分散」?要看需求而定
- 使用QStyle高端定制弹出菜单 QMenu源码剖析(二)
- 字符串
- 程序员加薪的技巧
- 数据存放在云端真的安全嘛?
- 程序员上下班途中都在想什么
- 当程序员写不出代码了,该怎么办?
- 程序员薪酬到底有多高?来看硅谷的工程师统计
- spring详细进阶之IOC
- ros 下面使用单目标定工具箱来进行标定摄像头.
- 欢迎使用CSDN-markdown编辑器