搜尋
  • 登入
  • 報名
密碼重置成功

關注您感興趣的項目並了解有關它們的最新消息

C++ 字串

收藏 154
閱讀 53381
更新時間 2016-09-11

C++ 提供了以下兩種類型的字串表示形式:

  • #C 風格字串

  • C++ 引入的string 類別類型

C 風格字串

C 風格的字串起源於C 語言,並在C++ 中繼續被支援。字串實際上是使用 null 字元 '\0' 終止的一維字元陣列。因此,以 null 結尾的字串,包含了組成字串的字元。

下面的宣告和初始化創建了一個 "Hello" 字串。由於在數組的末尾存儲了空字符,所以字符數組的大小比單字 "Hello" 的字符數多一個。

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '
char greeting[] = "Hello";
'};

依據陣列初始化規則,您可以把上面的語句寫成以下語句:

#include <iostream>

using namespace std;

int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '
Greeting message: Hello
'};    cout << "Greeting message: ";    cout << greeting << endl;    return 0; }

以下是C/C++ 中定義的字串的記憶體表示:

string_representation.jpg

#其實,您不需要把null 字元放在字串常數的末尾。 C++ 編譯器會在初始化陣列時,自動把 '\0' 放在字串的最後。讓我們嘗試輸出上面的字串:

#include <iostream>
#include <cstring>

using namespace std;

int main ()
{
   char str1[10] = "Hello";
   char str2[10] = "World";
   char str3[10];
   int  len ;

   // 复制 str1 到 str3
   strcpy( str3, str1);
   cout << "strcpy( str3, str1) : " << str3 << endl;

   // 连接 str1 和 str2
   strcat( str1, str2);
   cout << "strcat( str1, str2): " << str1 << endl;

   // 连接后,str1 的总长度
   len = strlen(str1);
   cout << "strlen(str1) : " << len << endl;

   return 0;
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

C++ 中有大量的函數用來操作以null結尾的字串:supports a wide range of functions that manipulate null-terminated strings:

##1#複製字串s2 到字串s1。 2連接字串 s2 到字串 s1 的結尾。 3傳回字串 s1 的長度。 4如果s1 和s2 是相同的,則回傳0;如果s1< s2 則回傳小於0;如果s1>s2 則回傳大於0。 5傳回一個指針,指向字串s1 中字元ch 的第一次出現的位置。 6傳回一個指針,指向字串s1 中字串s2 的第一次出現的位置。
序號
strcpy(s1, s2);
strcat(s1, s2);
strlen(s1);
strcmp(s1, s2);
strchr(s1, ch);
strstr(s1, s2);
###

下面的實例使用了上述的一些函數:

#include <iostream>
#include <string>

using namespace std;

int main ()
{
   string str1 = "Hello";
   string str2 = "World";
   string str3;
   int  len ;

   // 复制 str1 到 str3
   str3 = str1;
   cout << "str3 : " << str3 << endl;

   // 连接 str1 和 str2
   str3 = str1 + str2;
   cout << "str1 + str2 : " << str3 << endl;

   // 连接后,str3 的总长度
   len = str3.size();
   cout << "str3.size() :  " << len << endl;

   return 0;
}

當上面的程式碼被編譯和執行時,它會產生下列結果:

str3 : Hello
str1 + str2 : HelloWorld
str3.size() :  10

C++ 中的String 類別

C++ 標準函式庫提供了string 類別類型,支援上述所有的操作,另外還增加了其他更多的功能。我們將學習C++ 標準庫中的這個類,現在讓我們先來看看下面這個實例:

現在您可能還無法透徹地理解這個實例,因為到目前為止我們還沒有討論類別和對象。所以現在您可以只是粗略地看下這個實例,等理解了物件導向的概念之後再回頭來理解這個實例。

rrreee

當上面的程式碼被編譯和執行時,它會產生下列結果:

rrreee
熱AI工具
Undress AI Tool
Undress AI Tool

免費脫衣圖片

AI Clothes Remover
AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undresser.AI Undress
Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

Stock Market GPT
Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱門工具
記事本++7.3.1
記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版
SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1
禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6
Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版
SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)