string class in C++
some functions about string
class
#include<iostream>
#include<string>
using namespace std;
int main(){
string s = "xiaohaha";
string s1 = "_and";
s += s1;//you can also use "s.append(b)" to add two strings
cout<<s.size()<<endl;//equals s.length()
cout<<s.substr(4,4)<<endl;//s.substr([pos,]len)
s1 = "boy*";
cout<<s.insert(0,s1)<<endl;//s.insert(pos,str),return this string
cout<<s.find("haha")<<endl;//s.find(str[,pos]),return -1 if not exist
//transform string to character array
char arr[20];
int len = s.copy(arr,19);
arr[len] = '\0';
//strncpy(arr,s.c_str(),10);
cout<<arr;
return 0;
}
read a line
when using fgets(arr,sizeof(arr),stdin)
or gets(arr)
to read a line,if you don’t deal with the \n
in the previous line, it is easy to occur some mistake,below is a way you can avoid this situation.
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int num;
char arr[20];
scanf("%d\n",&num);//not scanf("%d",&num);
fgets(arr,sizeof(arr),stdin);
return 0;
}