如何使用strspn来查找strspn的arg 2中提到的字符数以外的字符数?

时间:2016-02-12 16:13:11

标签: c string

如何计算除strspn函数中提到的值以外的值的数量?我知道strspn计算其参数2中提到的字符的出现总数,但我想做与之相反的事情。

例如,如果我有字符串:ABCDEFGH

我想计算D以外的字符数。所以答案是:7

无论如何,我可以使用strspn执行此操作吗?

3 个答案:

答案 0 :(得分:1)

你想要计算与该集不匹配的字符数,你需要自己实现这个函数,循环:

size_t count_non_matching_chars(const char *str, const char *set) {
    size_t pos = 0, count = 0, chunk;

    while (str[pos] != '\0') {
        pos += strspn(str + pos, set);  /* skip the matching chars */
        chunk = strcspn(str + pos, set); /* count non matching chars */
        pos += chunk;
        count += chunk;
    }
    return count;
}

以下是仅使用strspn()的替代方案,如果有许多不匹配的字符,效率会稍低:

size_t count_non_matching_chars(const char *str, const char *set) {
    size_t pos = 0, count = 0;
    for (;;) {
        pos += strspn(str + pos, set);  /* skip the matching chars */
        if (str[pos] == '\0')
            break;
        count++;  /* count and skip the non-matching character */
        pos++;
    }
    return count;
}

答案 1 :(得分:-1)

尝试从字符串的总长度中减去strspn的结果:

// imgW and imgH are the width and height of the desired ultimate image
public BufferedImage combineImages(List<BufferedImage> docList, int imgW, int imgH) {
    // first create the main image that you want to draw to
    BufferedImage mainImg = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);

    // get its Graphics context
    Graphics g = mainImage.getGraphics();

    int intx = 0;
    int inty = 0;

    // draw your List of images onto this main image however you want to do this
    for (BufferedImage eachImage : docList){
            g.drawImage(eachImage, 0,inty,imageWidth,imageHeight,null);
            intx += eachImage.getWidth();
            inty += eachImage.getHeight() * zoomAdd;
        }
    }

    // anything else that you need to do

    g.dispose(); // dispose of this graphics context to save resources

    return mainImg;
}

答案 2 :(得分:-1)

使用与strcspn(str, set)类似的strspn(str, set)功能,但可以使用set的补码。请注意,终止'\0'set的隐含部分,因此不会被strcspn()计算。