c语言程序设计编写函数void funchar s char s1 char s2将s所指向的字符串中的数字转化为数字串存放在s1所指向区域字母字符转化为字符串存放在s2所指向的区域。主函数中输入字符串调用函数后输出转换后结果。【输入形式】字符串【输出形式】分离结果
分析:需要遍历字符串中的每个字符,判断是数字还是字母,然后将数字转化为数字字符串,将字母转化为字符字符串。最后将转换后的字符串输出即可。
代码如下:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void fun(char *s, char *s1, char *s2) {
int i1 = 0, i2 = 0; // 记录s1和s2的下标
while (*s != '\0') {
if (isdigit(*s)) { // 是数字
*(s1 + i1) = *s; // 将数字转换为数字字符
i1++;
} else if (isalpha(*s)) { // 是字母
*(s2 + i2) = *s; // 将字母转换为字符字符串
i2++;
}
s++; // 指针后移
}
*(s1 + i1) = '\0'; // 字符串结尾
*(s2 + i2) = '\0';
}
int main() {
char s[100], s1[100], s2[100];
printf("请输入字符串:");
gets(s); // 输入字符串
fun(s, s1, s2); // 调用函数
printf("数字字符串:%s\n", s1);
printf("字母字符串:%s\n", s2);
return 0;
}
注意:本题中输入字符串使用了gets函数,该函数存在安全性问题,建议使用更安全的fgets函数
原文地址: https://www.cveoy.top/t/topic/fGpD 著作权归作者所有。请勿转载和采集!