zoukankan      html  css  js  c++  java
  • C++ code:char pointers and char arrays(字符指针与字符数组)

    C-串的正确赋值、复制、修改、比较、连接等方式。

     1 #include<iostream>
     2 #pragma warning(disable: 4996)//这一句是为了解决“strrev”出现的警告
     3 using namespace std;
     4 int main()
     5 {
     6     char* s1 = "Hello ";
     7     char* s2 = "123";
     8     char a[20];
     9     strcpy(a,s1);
    10     cout << (strcmp(a, s1) == 0 ? "" : " not") << "equal
    ";
    11     cout << strcat(a, s2) << endl;
    12     cout << strrev(a) << endl;
    13     cout << strset(a, 'c') << endl; 
    14     cout << (strstr(s1, "ell") ? "" : "not ") << "found
    ";
    15     cout << (strchr(s1, 'c') ? "" : "not ") << "found
    ";
    16     cin.get();
    17     return 0;
    18 }

    运行结果:

    下面进入string:

    string是一种自定义的类型,它可以方便地执行C-串不能直接执行的一切操作。它处理空间占用问题是自动的,需要多少,用多少,不像字符指针那样,提心吊胆于指针脱钩时的空间游离。

     1 #include<iostream>
     2 #include<string>
     3 #include<algorithm>
     4 using namespace std;
     5 int main()
     6 {
     7     string a,s1 = "Hello ";
     8     string s2 = "123";
     9     a=s1;//复制
    10     cout << (a==s1 ? "" : " not") << "equal
    ";//比较
    11     cout << a + s2 << endl;//连接
    12     reverse(a.begin(), a.end());//倒置串
    13     cout << a << endl; 
    14     cout << a.replace(0, 9, 9, 'c') << endl;//设置
    15     cout << (s1.find("ell")!=-1 ? "" : "not ") << "found
    ";//查找串
    16     cout << (s1.find("c") != -1 ? "" : "not ") << "found
    ";//查找字符
    17     cin.get();
    18     return 0;
    19 }

    运行结果:

  • 相关阅读:
    .NetTiers不支持UDT的解决方式
    CreateRemoteThread的问题
    使用.NetTiers的事务
    how do i using c# to obtain call stack on crash?
    使用C#为进程创建DUMP文件
    GTD软件
    c#调用c++的dll
    使用PowerDesigner生成数据库
    笨鸟学iOS开发(2)ApplicationSettings
    让IIS支持中文名
  • 原文地址:https://www.cnblogs.com/ariel-dreamland/p/9018511.html
Copyright © 2011-2022 走看看