C语言字符串处理:数字与字母分离

问题描述:

编写函数void fun(char *s, char *s1, char *s2),将s所指向的字符串中的数字转化为数字串存放在s1所指向区域,字母字符转化为字符串存放在s2所指向的区域。主函数中输入字符串,调用函数后输出转换后结果。

输入形式:

字符串

输出形式:

分离结果

样例输入:

'a1b2c3*h8h7g6'

样例输出:

123876 abchhg

解题思路:

遍历字符串,判断每个字符是数字还是字母,将数字拼成数字串存放在s1所指向的区域中,将字母存放在s2所指向的区域中。

参考代码:

#include <stdio.h>
#include <string.h>

void fun(char *s, char *s1, char *s2) {
    int i = 0;
    int j = 0;
    int k = 0;
    while (s[i] != '\0') {
        if (s[i] >= '0' && s[i] <= '9') {
            s1[j++] = s[i];
        } else if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')) {
            s2[k++] = s[i];
        }
        i++;
    }
    s1[j] = '\0';
    s2[k] = '\0';
}

int main() {
    char s[100];
    char s1[100];
    char s2[100];
    printf("输入字符串:");
    gets(s);
    fun(s, s1, s2);
    printf("分离结果:\n");
    printf("%s\n", s1);
    printf("%s\n", s2);
    return 0;
}
C语言字符串处理:数字与字母分离

原文地址: https://www.cveoy.top/t/topic/omaR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录