C++字符串

在C++中,字符串(string)是一個表示字符序列的std::string類的對象。可以對字符串執行許多操作,如:串聯,比較,轉換等。

C++字符串示例

下面來看看看C++字符串的簡單例子。

#include <iostream>  
using namespace std;  
int main( ) {  
    string s1 = "Hello";    
        char ch[] = { 'C', '+', '+'};    
        string s2 = string(ch);    
        cout<<s1<<endl;    
        cout<<s2<<endl;    
}

執行上面示例代碼得到如下結果 -

Hello
C++

C++字符串比較示例

下面來看看看使用strcmp()函數的字符串比較的簡單例子。

#include <iostream>  
#include <cstring>  
using namespace std;  
int main ()  
{  
  char key[] = "mango";  
  char buffer[50];  
  do {  
     cout<<"What is my favourite fruit? ";  
     cin>>buffer;  
  } while (strcmp (key,buffer) != 0);  
 cout<<"Answer is correct!!"<<endl;  
  return 0;  
}

執行上面示例代碼得到如下結果 -

What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

C++字符串Concat示例

下面來看看看使用strcat()函數的字符串連接的簡單示例。

#include <iostream>  
#include <cstring>  
using namespace std;  
int main()  
{  
    char key[25], buffer[25];  
    cout << "Enter the key string: ";  
    cin.getline(key, 25);  
    cout << "Enter the buffer string: ";  
     cin.getline(buffer, 25);  
    strcat(key, buffer);   
    cout << "Key = " << key << endl;  
    cout << "Buffer = " << buffer<<endl;  
    return 0;  
}

執行上面示例代碼得到如下結果 -

Enter the key string: Welcome to
Enter the buffer string:  C++ Programming.
Key = Welcome to C++ Programming.
Buffer =  C++ Programming.

C++字符串複製示例

下面來看看看使用strcpy()函數複製字符串的簡單示例。

#include <iostream>  
#include <cstring>  
using namespace std;  
int main()  
{  
    char key[25], buffer[25];  
    cout << "Enter the key string: ";  
    cin.getline(key, 25);  
    strcpy(buffer, key);  
    cout << "Key = "<< key << endl;  
    cout << "Buffer = "<< buffer<<endl;  
    return 0;  
}

執行上面示例代碼得到如下結果 -

Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial

C++字符串長度示例

下面來看看看使用strlen()函數計算字符串長度的簡單示例。

#include <iostream>  
#include <cstring>  
using namespace std;  
int main()  
{  
    char ary[] = "Welcome to C++ Programming";  
    cout << "Length of String = " << strlen(ary)<<endl;  
    return 0;  
}

執行上面示例代碼得到如下結果 -

Length of String = 26