C++ 字符串截断的实现(基础函数)

C++ 字符串截断的实现(基础函数)


DATE: 2018-01-19 14:51:24

C++ 字符串截断的实现

#include <stdio.h>
#include <string>
#include <string.h>
using namespace std;
/*
 * str: 待分隔的原始字符串
 * pos: 分隔位置
 * lor: 截取字符串左侧部分(-1) or 右侧部分(1)
 * */
string cutString(string str, int pos, int lor)
{
    if (lor < 0)
    {
        string s = str;
        string ss = s.substr(0, pos);
        return ss;
    }
    if (lor > 0)
    {
        string s = str;
        int len = 0;
        len = strlen(s.c_str());
        string ss = s.substr(pos, len);
        return ss;
    }
}

int main()
{
    string str = "if you have a dream, you";
    string left;
    string right;
    left = cutString(str, 5, -1);
    right = cutString(str, 5, 1);
    printf("%s\n", left.c_str());
    printf("%s\n", right.c_str());
    return 0;
}
版权声明

弈心博客


本文首发site_name,转载请附上博文链接!