如何将字符串的内容剪切到特定的字符串或位置?

时间:2015-03-22 15:17:59

标签: c++ linux

经过我所有的研究,我来这里剪掉这个字符串:

{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread|./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....

到字符串:

./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....

以下是我的代码:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

    void func(std::ostream&obj){
        std::string dbgmsg =  dynamic_cast<std::ostringstream&>(obj).str();
        cout << dbgmsg; //I need to convert this string to ./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....
    }

    int main() {

        std::ostringstream ss;
        ss <<"{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread|./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....";
        func(ss);

        return 0;
    }

My GCC:gcc version 4.5.3(GCC)

3 个答案:

答案 0 :(得分:0)

最后我找到了解决办法:)这就是:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

void func(std::ostream&obj){
    std::string dbgmsg =  dynamic_cast<std::ostringstream&>(obj).str();     
    std::size_t pos = dbgmsg.find("./");
    std::string str3 = dbgmsg.substr (pos);
    cout << str3; //now o/p :  ./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....
}

int main() {

    std::ostringstream ss;
    ss <<"{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread||./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....";
    func(ss);

    return 0;

}

答案 1 :(得分:0)

您可以使用find查找|的第4次出现,然后substring

void func(std::ostream&obj){
    std::string dbgmsg =  dynamic_cast<std::ostringstream&>(obj).str();
    int occurrences = 0;
    int start = 0;

    while (occurrences !=4 && (start = dbgmsg.find("|", start)) != string::npos) {
        ++occurrences;
        ++start; 
    }

    if (start != string::npos)
    {
        cout << dbgmsg.substr (start);
    }
}

答案 2 :(得分:0)

派对有点晚了,但这是我的解决方案

#include <iostream>
#include <string>

std::string getString(std::string fullString){
    int pos = 0;
    for(int i = 0; i < 4; i++){
        pos = fullString.find("|", pos+1);
    }
    return fullString.substr(pos+1);
}
int main( void ){
    std::string str("{[(2015/11/30|01:07:53.357|-1227639088|DefaultThread|./src/Myprogram.cpp:564|int main(int, argv**))]} Server Starting....");
    std::cout << getString(str) << std::endl;
    return 0;
}