C/C++字符串及函数

  1 #include <iostream>

  2 #include <string.h>             // define strcpy | strlen | strcmp

  3 //#include <string>             

  4 #include <cstdio>               // define printf

  5 using namespace std;

  6 

  7 int main()

  8 {

  9     // c strings (char arrays)

 10     char ch1[] = "guoling"; // initialization is ok

 11     // ch2[10] = "daniel";      // but char arrays cannot be assigned

 12     char ch2[10];

 13     char ch3[30] = "danield ";

 14     char* pch;

 15 

 16     // c-style char array input

 17     char ch4[20];

 18     cin.getline(ch4, 20);

 19     cout << "ch4: " << ch4 << endl;

 20 

 21     // cpp-style string input

 22     string s1;

 23     getline(cin, s1);

 24     cout << "s1: " << s1 << endl;

 25 

 26     string s2;

 27     s2 = ch1;

 28     cout << "s2: " << s2 << endl;

 29     strcpy(ch2, s2.c_str());

 30     cout << "ch2: " << ch2 << endl;

 31 

 32     strcpy(ch2, ch1);

 33     strcat(ch3, ch1);

 34     int result = strcmp(ch1, ch3);

 35     pch = strchr(ch3, 'd');

 36     while(pch != NULL)

 37     {

 38         printf("Found at %d/n", pch - ch3 + 1);

 39         pch = strchr(pch + 1, 'd');

 40     }

 41 

 42     if(result > 0)

 43     {

 44         printf("ch1 is greater than ch3/n");

 45     }

 46     else

 47     {

 48         printf("ch1 is smaller than ch3/n");

 49     }

 50 

 51     printf("ch1: %s/n", ch1);

 52     printf("The length of ch1: %d/n", strlen(ch1));

 53     printf("ch2: %s/n", ch2);

 54     printf("ch3: %s/n", ch3);

 55     // cout << "ch1 is: " << ch1 << endl;   // the same as the above

 56     // cout << "ch2 is: " << ch2 << endl;

 57 

 58     return 0;

 59 }

                                                                                                                                           27,10-13      Bot

/* output:
hello
ch4: hello
kitty
s1: kitty
s2: guoling
ch2: guoling
Found at 1
Found at 7
ch1 is greater than ch3
ch1: guoling
The length of ch1: 7
ch2: guoling
ch3: danield guoling
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值