一、C语言风格的字符串
1. C语言中没有字符串类型,所以字符串是用char型数组存储的:char s[ ]="abc";
char s[]="abc";
cout<<s<<endl; //输出 : abc
cout<<*s<<endl; //输出 : a
字符串"abc"使用的值就是这些字符的地址,而不是这些字符本身,所以字符串的首地址就是abc,也是s,s是数组的首地址&s[0]
其中s[0]="a" s[1]="b" s[2]="c"
2.
//由字符串的存储可知:name1是有四个元素的数组,“John” 将其首地址赋值给了name1
const char * name1= "John";
cout<<name1<<endl; //输出: John
cout<<*name1<<endl; //输出: J
3. int型数组就比较好理解了
int arr[]={1,2,3,4};
cout<<arr<<endl; //输出:0018FF30
cout<<*arr<<endl; //输出:1
二、C++风格的字符串
C++引入了string类,可以用库中的方法。但其本质也是数组,C语言风格的字符串的处理方法也可以使用。
string str="name";
cout<<str[1];//输出a
以下是一些自带的函数方法:
#include<iostream>
#include<string>
using namespace std;
void main(){
string str="ABC";
str.append("DEF");
cout<<"str="<<str<<endl;
int consequence = str.compare("ABC");
if(consequence>0)cout<<str<<">ABC"<<endl;
if(consequence<0)cout<<str<<"<ABC"<<endl;
if(consequence=0)cout<<str<<"=ABC"<<endl;
str.assign("123");
cout<<"str="<<str<<endl;
str.insert(1,"ABC");
cout<<"str="<<str<<endl;
cout<<str.substr(2,4)<<endl;
cout<<str.find("ABC")<<endl;
cout<<str.length()<<endl;
string str1="new String";
str.swap(str1);
cout<<"str="<<str<<",str1="<<str1<<endl;
//strcpy是数组存储字符串用来的
char str2[4];
char a[4]="ABC";//三个位置是不够用的
strcpy(str2,a);
cout<<str2<<endl;
}
运行结果: