Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

提取数字串按数值排序 #19

Open
Rain120 opened this issue Feb 11, 2022 · 0 comments
Open

提取数字串按数值排序 #19

Rain120 opened this issue Feb 11, 2022 · 0 comments

Comments

@Rain120
Copy link
Owner

Rain120 commented Feb 11, 2022

题目

给定一个字符串,请将其中的所有数字串提取,并将每个数字串作为整数看待(假设可以用int 表示),按从小到大顺序输出结果,输出的整数之间以逗号间隔。如果没有数字,则输出0

输入

在一行内输入一串符号,长度不大于300。输入数据保证提取的整数不超过10^9。

输出

从小到大排序的整数序列,如果没有数字,则输出0;

样例输入

*1234.345#6781ad9jk81-11101?aght88ir09kp

样例输出

整数包括 1234,345,6781,9,81,11101,88,9

9,9,81,88,345,1234,6781,11101

For 循环

function analysisNumber(str) {
    const ans = [];
    let cnt = 0;
    let pos = 0;

    for (let i = 0; i < str.length; i++) {
        if (str[i] >= '0' && str[i] <= '9') {
            let store = '';
            pos = i;

            while (str[i] >= '0' && str[i] <= '9' && i < str.length) {
                i++;
            }

            store = str.substr(pos, i - pos);
            ans[cnt++] = store;
        }
    }

    return ans.length > 0 ?
        ans.sort((a, b) => a - b).join(',') :
        0;
}

正则表达式

function analysisNumber(s) {
    const res = s.replaceAll(/\D/g, ',').split(',').filter(Boolean).sort((a, b) => a - b);

    return res.length > 0 ? res.join(',') : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant