C語言風格的字符串和C++風格的

一、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;
}

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章