1. 主页
  2. 文档
  3. C++教程
  4. C++字符串
  5. C++ 字符串

C++ 字符串

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++ 字符串连接示例

让我们看看使用 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

C++ 字符串函数

 

 

 

 

 

这篇文章对您有用吗? 1