zoukankan      html  css  js  c++  java
  • C++中string的find()函数的用法

    string的find()函数用于找出字母在字符串中的位置。

    find(str,position)

    find()的两个参数:

    str:是要找的元素

    position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素。

    可以不填第二个参数,默认从字符串的开头进行查找。

    返回值为目标字符的位置,当没有找到目标字符时返回npos。

    例1:找到目标字符的位置

    string s = "hello world!";
    cout << s.find("e") << endl;

    结果为:1

    例2:未找到目标字符

    string s = "hello world!";
    if (s.find("a") == s.npos) {
        cout << "404 not found" << endl;
    }

    结果为:404 not found

    例3:指定查找位置

    string s = "hello world!";
    cout << s.find("l",5) << endl;

    结果为:9

    从空格开始(包含空格)的后半部分字符串中寻找字符"l",结果找到了world中的"l"在整个字符串中的位置

    找到目标字符在字符串中第一次出现和最后一次出现的位置

    例4:

    string s = "hello world!";
    cout << "first time occur in s:"<<s.find_first_of("l") << endl;
    cout << "last time occur in s:" << s.find_last_of("l") << endl;

    结果为:

    first time occur in s:2
    last time occur in s:9

    反向查找:

    例5:

    string s = "hello world!";
    cout << s.rfind("l") << endl;

    结果为:9

    即从后往前第一次出现"l"的位置

    参考一下:https://www.cnblogs.com/wkfvawl/p/9429128.html

  • 相关阅读:
    老狼老狼几点了
    佐藤 Sato CL4NX 通过发送指令打印RFID标签
    HonyWell Intermec 通过Fingerprint指令打印RFID标签
    微信小程序中用echarts地图并点亮城市geo和effectScatter
    .NET Core
    数组去重
    Oracle
    CSS积累
    WebADNuke整理
    .net 基础面试题
  • 原文地址:https://www.cnblogs.com/cff2121/p/11579066.html
Copyright © 2011-2022 走看看