字符串相关操作

std::basic_string::substr

函数定义及功能描述

注: 默认参数npos means "until the end of the string"

示例程序

#include<iostream>
#include <string>

using namespace std;

int main()
{
    string t = "15:30:28";
    
    // 1 5 : 3 0 : 2 8
    // 0 1 2 3 4 5 6 7
    
    string h = t.substr(0, 2);
    string m = t.substr(3, 2);
    string s = t.substr(6);

    cout << h << ' ' << m << ' ' << s << endl;

    return 0;
}

std::basic_string::find

函数定义及功能描述

注:

  1. When pos is specified, the search only includes characters at or after position pos,注意当提供pos参数时,是包含pos那个位置的
  2. 可以 Find position of a character 也可以 Find position of a C string.
  3. If not found, returns npos,即-1

示例程序

#include<iostream>
#include <string>

using namespace std;

int main()
{
    string t = "15:30:28";

    // 1 5 : 3 0 : 2 8
    // 0 1 2 3 4 5 6 7
    
    int pos1 = t.find(':');
    int pos2 = t.find(':', pos1 + 1);

    cout << pos1 << ' ' << pos2 << endl;

    return 0;
}

std::basic_string::rfind

函数定义及功能描述

注:

  1. When pos is specified, the search only includes sequences of characters that begin at or before position pos, rfind是倒着找,仅考虑pos及以前的位置
  2. 可以 Find position of a character 也可以 Find position of a C string.
  3. If not found, returns npos,即-1

示例程序

#include<iostream>
#include <string>

using namespace std;

int main()
{
    string t = "15:30:28";

    // 1 5 : 3 0 : 2 8
    // 0 1 2 3 4 5 6 7

    int pos1 = t.rfind(':');
    int pos2 = t.rfind(':', pos1 - 1);

    cout << pos1 << ' ' << pos2 << endl;

    return 0;
}

std::string::c_str

函数定义及功能描述

注意:c_str()获取的结果为const char *

函数用途

有些情况下需要使用printf输出string,但是string作为一种类类型,其对象并非仅仅包含字符串,因此无法通过&获取到字符串的首地址
而使用c_str()即可获取到字符串的首地址

示例程序

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
    string str;
    cin >> str;
    printf("%s\n", str.c_str());
    return 0;
}

strcpy

函数定义及功能描述

注:这是一个C语言库函数

函数用途

用于向C字符数组(char *)中拷贝一个字符串的字面值常量(const char *)

示例程序

#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char str[4];
    strcpy(str, "123");
    printf("%s\n", str);
    return 0;
}

posted @ 2021-10-17 23:17  0x7F  阅读(44)  评论(0编辑  收藏  举报