(5)功能:编写函数void fun(char s[])将一个由四个数字组成的字符串转换为每两个数字间有一个空格的形式输出。 例如:输入“4567”,应输出“4□5□6□7”(□表示空格)。
时间: 2023-11-27 19:53:42 浏览: 96
以下是实现该功能的代码:
```c
#include <stdio.h>
#include <string.h>
void fun(char s[]) {
int len = strlen(s);
for(int i = 0; i < len; i++) {
printf("%c", s[i]);
if(i % 2 == 0 && i != len - 1) {
printf(" ");
}
}
}
int main() {
char s[] = "4567";
fun(s);
return 0;
}
```
输出结果为:
```
4 5 6 7
```
函数 `fun` 中,首先获取字符串的长度,然后遍历字符串中的每个字符,将其输出。当遍历到第偶数个字符时,输出一个空格。注意,最后一个字符不需要输出空格,因此需要特判一下。
相关问题
编写函数void fun(char s[]),其功能是将字符串s中的小写字母转换为大写字母
好的,这是一个简单的函数,可以使用循环遍历字符串s中的每个字符,如果字符是小写字母,则将其转换为大写字母。以下是函数的代码:
void fun(char s[]) {
int i = 0;
while (s[i] != '\0') {
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] - 'a' + 'A';
}
i++;
}
}
你可以将字符串作为参数传递给该函数,它将修改原始字符串并将其转换为大写字母。
编写函数:把一个字符串中的非数字字符取出,生成一个新的字符串。 函数接口定义: void fun(char *s);
以下是实现该函数的代码:
```c
#include <stdlib.h>
#include <string.h>
void fun(char *s) {
int len = strlen(s);
char *new_str = (char*)malloc(sizeof(char) * (len + 1)); // 申请新字符串的内存空间
int j = 0; // 记录新字符串的位置
for (int i = 0; i < len; i++) {
if (s[i] < '0' || s[i] > '9') { // 如果不是数字字符
new_str[j++] = s[i]; // 把它放到新字符串中
}
}
new_str[j] = '\0'; // 在新字符串末尾添加'\0'
strcpy(s, new_str); // 把新字符串复制回原字符串
free(new_str); // 释放新字符串的内存空间
}
```
函数的实现思路是先申请一个新字符串的内存空间,然后遍历原字符串,把非数字字符放到新字符串中。最后把新字符串复制回原字符串,并释放新字符串的内存空间。