zoukankan      html  css  js  c++  java
  • 判断一个字符串是否是另一个字符串的子串。

    STL中的find()函数,提供了强大的功能。

    当我们判断一个字符串是否包含另一个字符串的时候,可以使用find();

    如下图:

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string a="abcdefghigklmn";
        string b="def";
        string c="123";
        string::size_type idx;
         
        idx=a.find(b);//在a中查找b.
        if(idx == string::npos )//不存在。
            cout << "not found
    ";
        else//存在。
            cout <<"found
    "; 
        idx=a.find(c);//在a中查找c。
        if(idx == string::npos )//不存在。
            cout << "not found
    ";
        else//存在。
            cout <<"found
    "; 
        return 0;
    }

    当然了,上述的idx我们也可以定义成int类型.

    实际上,可能定义成int类型更符合我们的认知。代码如下:

        string str1="abcdefghigklmn";
        string str2="def";
        string str3="123";
        int idx = 0;
        idx = str1.find(str2);
        cout<<"index_str2 = "<<idx<<endl;
    
        idx = str1.find(str3);
        cout<<"index_str3 = "<<idx<<endl;

    我们看下输出结果:

     显然,str2是str1的字串,返回的是第一个匹配字符的索引;str3不是str1的子串,返回的是-1;因此,我们可以通过返回值idx来确定是不是子串!

    如果是子串,则返回非负整数

    如果不是子串,则返回-1;

  • 相关阅读:
    getopt for windows
    开源代码学习之Tinyhttpd
    GCC 中的编译器堆栈保护技术
    读《程序员的思维修炼》有感
    main之前初始化流程
    平均速度
    显示图案
    圆的面积和周长
    C#(Winform) Http 发送数据
    Android BaseAdapter的使用
  • 原文地址:https://www.cnblogs.com/shaonianpi/p/12733238.html
Copyright © 2011-2022 走看看