zoukankan      html  css  js  c++  java
  • 6.4 C++提取子字符串及字符串的比较

    参考:http://www.weixueyuan.net/view/6393.html

    总结:

      函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。

      “==”、 “!=”、 “<=”、 “>=”、 “<”和“>”操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。

    函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。

    例1:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string s1 = "first second third";
        string s2;
        s2 = s1.substr(6, 6);
        cout<< s1 <<endl;
        cout<< s2 <<endl;
        return 0;
    }

    程序运行结果:
    first second third
    second

    该函数同样会出现参数越界的情况,如果第一个参数越界则函数会抛出异常。在第一个参数没有越界的情况下,第二个参数仍然会导致越界,该函数的处理方式与前面提到的erase函数、replace函数相同,子字符串最多从第一个参数所指明的下标开始一直延续到字符串结尾。

    C++字符串的比较

    参考:http://www.weixueyuan.net/view/6395.html

    “==”、 “!=”、 “<=”、 “>=”、 “<”和“>”操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。

    例1:

     
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string s1 = "secondsecondthird";
        string s2 = "secondthird";
        if( s1 == s2 )
            cout<< " == " <<endl;
        if( s1 != s2 )
            cout<< " != " <<endl;
        if( s1 < s2 )
            cout<< " < " <<endl;
        if( s1 > s2 )
            cout<< " > " <<endl;
        return 0;
    }

    程序最终运行结果:
    !=
    <

  • 相关阅读:
    CHAR和HEX互相转换
    Delphi之TComponent类
    Delphi 延迟函数 比sleep 要好的多
    Delphi中三种延时方法及其定时精度分析
    Cport 应用集合
    重命名数据库时提示无法用排他锁锁定数据库
    Bugzilla在XP下安装
    Web service 超过了最大请求长度
    调用webservice时提示对操作的回复消息正文进行反序列化时出错
    c# IL 指令解析
  • 原文地址:https://www.cnblogs.com/yongpan/p/7919527.html
Copyright © 2011-2022 走看看