0

您好我正在尝试从较大的字符串中提取一个小字符串,基本上我得到了一个带有分隔符的字符串,我需要重新排列它。所以假设我有“@the President#”@ 显示我必须开始的地方,# 是子字符串的结尾。我正在使用 strchr 来获取指向 @ 符号的指针,并且我知道我需要搜索直到找到 # 符号。虽然没有从 x 到 y 的函数,但我不确定如何从 char 指针 a 转到符号 #。

    char *garbage = "@the president#";
    int count = 0;
    char a = strchr(garbage, @);
    char *sentence = NULL;
    while(start at a, garbage[count] != #){
       char sentence[count] = garbage[count];
       count++;
    }
4

1 回答 1

5

使用这样的东西:

const char* posAtSign = strchr(searchString,'@');
if (posAtSign != NULL) {
    const char* posPoundSign = strchr(posAtSign+1,'#');
    if (posPoundSign != NULL) {
        const int numChars = posPoundSign - posAtSign - 1;
        strncpy(substringBuffer,posAtSign+1,numChars);
    }
}

测试代码:

char searchString[] = "@the president#";
char substringBuffer[128];

const char* posAtSign = strchr(searchString,'@');
if (posAtSign != NULL) {
    const char* posPoundSign = strchr(posAtSign+1,'#');
    if (posPoundSign != NULL) {
        const int numChars = posPoundSign - posAtSign - 1;
        strncpy(substringBuffer,posAtSign+1,numChars);
        substringBuffer[numChars] = '\0';
        printf("substring: '%s'", substringBuffer);
    }
}
于 2013-07-09T18:01:06.043 回答