C++ 如何获取字符*的一部分?

C++ 如何获取字符*的一部分?,c++,string,char,tesseract,C++,String,Char,Tesseract,下面的代码使用Tesseract解决了一个小图像 char *answer = tess_api.GetUTF8Text(); 我事先知道结果总是以字符“+”开头,它是一个单词,所以我想清除它找到的任何垃圾 我得到的结果是“G+ABC S\n\n”,我只需要+ABC。所以基本上我需要忽略第一个空格之前的所有内容。我想我应该使用rindex来查找+和空格的位置。您可以使用: // just scan "answer" to find out where to start and where to

下面的代码使用Tesseract解决了一个小图像

char *answer = tess_api.GetUTF8Text();
我事先知道结果总是以字符“+”开头,它是一个单词,所以我想清除它找到的任何垃圾

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

您可以使用:

// 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"
您可以查看其他替代方案

附言:在
C++
中使用
string
,这会更容易(请查看@DavidSykes的答案)

如果你真的不能使用字符串,那么像这样的东西就可以了

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;
}

您可能应该使用
std::string
,这要简单得多。如果
tess_api.GetUTF8Text()
的结果是一个带有uft8字符的字符串,最好使用
wchar*
而不是
char*
我只希望使用大写字母。我不希望有任何utf8字符,所以我使用了tess_api.SetVariable(“tessedit_char_whitelist”、“+ABCDEFGHIjklmnopqrstuvxyz”);结果可以具有可变长度。“+”前面可以有多个字母,或者根本没有,因此我需要从+到单词末尾的所有内容(换行符或空格);超出已分配内存末尾的写入main.cpp:222:44:错误:从“void*”到“char*”[-fppermissive]char*dataYouWant=malloc(长度+1)的转换无效;如何获取indexStart和indexEnd的值?我是否使用rindex?@Crypto您应该使用
strlen
获取长度。不确定字符串
“G+”
是否为有效输入,但这会导致此算法出现问题。@Lundin为什么这么说?在第一个+啊-是的,实际上这不会是一个问题,而是在没有找到两个符号的情况下搜索空间。但问题并没有提到这种错误处理是必需的,所以别担心:)
+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;
}