C++代码Scratches

字符、字符串分割字符串

#include <iostream>
#include <vector>
using std::string;
using std::vector;


//此方法用于char时,将第二个参数类型改为char,separator.size()改为 1 即可
vector<string> split_str(const string& src , const string& separator)
{
    size_t pos = 0;
    size_t start_pos = 0;
    vector<string> result_str;
    while((pos = src.find(separator, start_pos)) != string::npos)   //只要找得到separator
    {
        result_str.emplace_back(src.substr(start_pos, pos - start_pos));
        start_pos = pos + separator.size();
    }
    result_str.emplace_back(src.substr(start_pos, src.size() - start_pos));
    return result_str;
}

int main() {
    string s1 = "afsa@hnjasdf@fjsdf";
    vector<string> re1 = split_str(s1,"@");
    for(const auto& s : re1)
    {
        std::cout << s << std::endl;
    }

    std::cout << "---------------" << std::endl;

    string s2 = "asdf#@#sdghdf#@#hsdfags#@#ampk#@#123";
    vector<string> re2 = split_str(s2,"#@#");
    for(const auto& s : re2)
    {
        std::cout << s << std::endl;
    }

    return 0;
}

读取文件所有内容

void readall(const char* filepath, std::string& str)
{
    FILE* file;
    fopen_s(&file,filepath, "r");
    if (!file)  return;

    struct stat st;
    memset(&st, 0, sizeof(st));
    stat(filepath, &st);
    size_t filesize = st.st_size;
    if (filesize == 0)  return;
    str.resize(filesize);
    fread((void*)str.data(), 1, filesize, file);
    fclose(file);
}
使用:
 string s;
 readall("config.h",s);
 cout << s;

读取文件索引区间内容

void readrange(const char* filepath, std::string& str, size_t from = 0, size_t to = 0)
{
    FILE* file;
    fopen_s(&file,filepath, "r");
    if (!file)  return;

    struct stat st;
    memset(&st, 0, sizeof(st));
    stat(filepath, &st);
    size_t filesize = st.st_size;
    
    if (filesize == 0) return;
    if (to == 0 || to >= filesize) to = filesize - 1;
    size_t readbytes = to - from + 1;
    str.resize(readbytes);
    fseek(file, from, SEEK_SET);
    fread((void*)str.data(), 1, readbytes, file);
    fclose(file);
}

C FILE getline

bool readline(FILE* fp, std::string& str) {
    str.clear();
    char ch;
    while (fread(&ch, 1, 1, fp)) {
        if (ch == '\n') {
            // unix: LF
            return true;
        }
        if (ch == '\r') {
            // dos: CRLF
            // read LF
            if (fread(&ch, 1, 1, fp) && ch != '\n') {
                // mac: CR
                fseek(fp, -1, SEEK_CUR);
            }
            return true;
        }
        str += ch;
    }
    return str.length() != 0;
}
posted @ 2022-12-30 15:13  YiXiaoKezz  阅读(45)  评论(0编辑  收藏  举报