You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C/C++/Java/C#/Python实现字符串纯整数个数统计功能

多语言process函数实现:统计字符串中纯整数个数

规则说明

纯整数定义:1个及以上连续0-9阿拉伯数字组成的序列,忽略正负号、小数点及其他复杂数字格式,只要出现连续数字就算独立计数。
示例验证:输入字符串 I will eat 2 burgers 23 fries & 1.25 cokes l8r,输出结果为5,对应计数项为2、23、1、25、8。


C 语言

int process(const char* str) {
    int count = 0;
    int in_number = 0; // 标记当前是否处于连续数字序列中
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] >= '0' && str[i] <= '9') {
            if (!in_number) {
                count++;
                in_number = 1;
            }
        } else {
            in_number = 0;
        }
    }
    return count;
}

C++

#include <string>
#include <cctype>

int process(const std::string& str) {
    int count = 0;
    bool in_number = false;
    for (char c : str) {
        if (std::isdigit(c)) {
            if (!in_number) {
                count++;
                in_number = true;
            }
        } else {
            in_number = false;
        }
    }
    return count;
}

Java

public class Processor {
    public static int process(String str) {
        int count = 0;
        boolean inNumber = false;
        for (char c : str.toCharArray()) {
            if (Character.isDigit(c)) {
                if (!inNumber) {
                    count++;
                    inNumber = true;
                }
            } else {
                inNumber = false;
            }
        }
        return count;
    }
}

C#

public class Processor {
    public static int Process(string str) {
        int count = 0;
        bool inNumber = false;
        foreach (char c in str) {
            if (char.IsDigit(c)) {
                if (!inNumber) {
                    count++;
                    inNumber = true;
                }
            } else {
                inNumber = false;
            }
        }
        return count;
    }
}

Python

基础遍历实现

def process(s: str) -> int:
    count = 0
    in_number = False
    for c in s:
        if c.isdigit():
            if not in_number:
                count += 1
                in_number = True
        else:
            in_number = False
    return count

正则表达式简化实现

import re

def process(s: str) -> int:
    # \d+ 匹配1个及以上连续数字,findall返回所有匹配项列表,长度即为计数结果
    return len(re.findall(r'\d+', s))

内容的提问来源于stack exchange,提问作者souravbanerjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:24:06