cpp 专题
专题目录
您的位置:cpp > cpp 专题 > C++字符串
C++字符串
作者:--    发布时间:2019-11-20

在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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册