我如何获得char *的一部分?

时间:2014-01-29 08:38:17

标签: c++ string char tesseract

我有以下使用Tesseract解决小图像的代码。

char *answer = tess_api.GetUTF8Text();

我事先知道结果将始终以字符'+'开头,而且它是一个单词所以我想摆脱它找到的任何垃圾。

我得到的结果是“G + ABC S \ n \ n”,我只需要+ ABC。所以基本上我需要忽略+之前的所有内容以及第一个空格之后的所有内容我在想我应该使用rindex找到+和空格的位置。

2 个答案:

答案 0 :(得分:3)

std::string ParseString(const std::string& s)
{
    size_t plus = s.find_first_of('+');
    size_t space = s.find_first_of(" \n", plus);

    return s.substr(plus, space-plus);
}

int main()
{
    std::cout << ParseString("G+ABC S\n\n").c_str() << std::endl;
    std::cout << ParseString("G +ABC\ne\n").c_str() << std::endl;

    return 0;
}

给出

+ABC
+ABC

如果你真的不能使用字符串,那么这样的事情可能会

char *ParseString2(char *s)
{
    int plus,end;
    for (plus = 0 ; s[plus] != '+' ; ++plus){}
    for (end = plus ; s[end] != ' ' && s[end] != '\n' ; ++end){}
    char *result = new char[end - plus + 1];
    memcpy(result, s + plus, end - plus);
    result[end - plus] = 0;
    return result;
}

答案 1 :(得分:1)

您可以使用:

// just scan "answer" to find out where to start and where to end
int indexStart = // find the index of '+'
int indexEnd = // find the index before space

int length = indexEnd-indexStart+1;
char *dataYouWant = (char *) malloc(length+1);  // result will be stored here
memcpy( dataYouWant, &answer[indexStart], length ); 
                                     // for example answer = "G+ABC S\n\n"
dataYouWant[length] = '\0';          // dataYouWant will be "+ABC"

您可以查看Strings in c, how to get subString了解其他替代方案。

P.S。建议:在string中使用C++,这将更加容易(请查看@ DavidSykes的回答)。

相关问题