歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++中字符數組和字符串string

C++中字符數組和字符串string

日期:2017/3/1 9:38:02   编辑:Linux編程

字符數組

C++中字符數組用char str[]可以用來表示一個字符串。

(1) 數組的大小和字符串的長度。

數組的大小一定要大於字符串的長度,因為系統會自動補上一個’\0’作為字符串的結束標志。當然對於未初始化的也補’\0’.

#include <iostream>
#include <string>

using namespace std;

int main()
{
char str[11] = "I am happy"; // 系統會自動補上'\0'空字符作為結束標志,,未有初始化的也補'\0'
//char str[10] = "I am happy"; // 出錯 系統自動補上'\0' 此時字符數組長度不夠
//char str[13] = "I am happy"; // 後面未有初始化的也補上'\0' 為 I am happy\0\0\0
if(str[10] == '\0')
{
cout << "hello world!!" << endl;
}

cin >> str; // 輸入輸出
cout << str << endl;
return 0;
}

(2)getline()

getline函數可以讀取文本或者輸入流的一行,此時包括前面輸入的空格,只到回車換行才結束

#include <fstream>
#include <iostream>
#include <string>

using namespace std;
int main()
{
ifstream in("E:\\algorithmZack\\testString\\input.txt");
if(!in)
{
cerr << "some errors happened";
return -1;
}
string str;
while(getline(in, str)) /// getline 從文件input.txt中按行讀取文件
// while(getline(cin, str)) // 從輸入流中按行讀取 不包括換行符
{
cout << str << endl;
}
return 0;
}

(3)比較,連接,賦值,實際長度用函數strcmp, strcat, strcpy,strlen

參見:http://www.linuxidc.com/Linux/2014-11/108798.htm

字符串string

(1)String可以看做一個類庫,需要有包含頭文件#include <string>.

操作包括:連接(+=,append) 賦值(=, assign) 比較(>=,compare) 查找(find)

替換(replace) 刪除(erase) 插入(insert) 字串(substring) 交換(swap)

特性(length sizec_str) 正反向迭代器(interatorreverse_iterator)

其中使用append,assign,compare的好處在於參數可以為字符數組

詳細見:http://www.linuxidc.com/Linux/2012-01/52537.htm

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2014-11/108799p2.htm

Copyright © Linux教程網 All Rights Reserved