题目来源于提问者描述
输入一串字符串:7fGhs4,h
搞一串函数int process(char str1[]),使得非英文字母的在前面(输出:74,Ghsh)
且输出非英文字母的个数
题解如下
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *word = NULL, *other = NULL;
int process(char str[])
{
static int wordcount = 0;
static int othercount = 0;
char s;
s = *str;
if (s > 64 && s < 91 || s > 96 && s < 123)
{
word = realloc(word, wordcount + 2);
word[wordcount] = s;
wordcount++;
word[wordcount] = '\0';
}
else
{
other = realloc(other, othercount + 2);
other[othercount] = s;
othercount++;
other[othercount] = '\0';
}
return othercount;
};
int main()
{
int count;
char s, *str = &s;
s = getchar();
while (s != '\n')
{
count = process(str);
s = getchar();
}
str = malloc(strlen(word) + strlen(other) + 1);
str[0] = '\0';
str = strcat(str, other);
str = strcat(str, word);
puts(str);
printf("%d\n", count);
free(word);
free(other);
free(str);
return 0;
}可以注意到要求的函数类型是 int ,传参是一个 str[] ,借用这个数组的输入,不难想到数组在传参时退化为指针,利用指针和getchar()有序读取标准输入缓冲区的特性即可。
其实难点在于如何将连续的输入划分为分立的char进行处理,知道这一点之后就可以操作输入得到想要的输出了。