
根据这三张图片中的要求,用c语言写出代码,输入输出符合图片中的案例和要求


关注1,字符串中的连续数字提取
#include <stdio.h>
#include <ctype.h>
int main() {
char input[256];
fgets(input, sizeof(input), stdin); // 读取输入字符串
char result[256]; // 存储结果字符串
int count = 0; // 记录连续数字字符串的个数
int index = 0; // 记录结果字符串的位置
int i = 0;
while (input[i] != '\0') {
if (isdigit(input[i])) { // 如果当前字符是数字
int start = i; // 记录连续数字字符串的起始位置
int len = 0; // 记录连续数字字符串的长度
while (isdigit(input[i])) { // 继续向后检查连续数字字符串的长度
len++;
i++;
}
if (len >= 2) { // 如果连续数字字符串的长度大于等于2
for (int j = start; j < start + len; j++) { // 将连续数字字符串复制到结果字符串中
result[index++] = input[j];
}
count++; // 连续数字字符串个数加1
if (input[i] != '\0') { // 如果当前字符不是结束符,加上逗号分隔
result[index++] = ',';
}
}
} else {
i++;
}
}
if (index > 0 && result[index-1] == ',') { // 判断最后一个字符是否为逗号
result[index-1] = '\0'; // 去掉最后一个逗号
} else {
result[index] = '\0'; // 在结果字符串的末尾添加结束符
}
printf("%s\n", result); // 输出结果字符串
printf("%d\n", count); // 输出连续数字字符串的个数
return 0;
}
2,字符串位移
#include <stdio.h>
#include <string.h>
void rightShift(char* str, int n) {
int len = strlen(str);
n = n % len; // 取余是为了处理 n 大于字符串长度的情况
char temp[n]; // 用于保存右移的字符
memcpy(temp, str + len - n, n); // 使用 memcpy 函数将右移的字符拷贝到 temp 数组中
memmove(str + n, str, len - n); // 使用 memmove 函数将剩余字符向右移动
memcpy(str, temp, n); // 使用 memcpy 函数将右移的字符放到最左边
}
int main() {
char str[51];
int n;
scanf("%s", str); // 输入字符串
scanf("%d", &n); // 输入右移位数
rightShift(str, n); // 字符串右移
printf("%s\n", str); // 输出右移后的字符串
return 0;
}
3,指针数组的排序
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 40
#define NUM_COUNTRIES 10
void swap(char **str1, char **str2) {
char *temp = *str1;
*str1 = *str2;
*str2 = temp;
}
void sort_by_length(char **ptr_arr) {
int i, j;
for (i = 0; i < NUM_COUNTRIES-1; i++) {
for (j = 0; j < NUM_COUNTRIES-i-1; j++) {
if (strlen(ptr_arr[j]) > strlen(ptr_arr[j+1])) {
swap(&ptr_arr[j], &ptr_arr[j+1]);
}
}
}
}
void sort_by_ascii(char **ptr_arr) {
int i, j;
for (i = 0; i < NUM_COUNTRIES-1; i++) {
for (j = 0; j < NUM_COUNTRIES-i-1; j++) {
if (strcmp(ptr_arr[j], ptr_arr[j+1]) > 0) {
swap(&ptr_arr[j], &ptr_arr[j+1]);
}
}
}
}
int main() {
char countries[NUM_COUNTRIES][MAX_LEN];
char* ptr_arr_length[NUM_COUNTRIES];
char* ptr_arr_ascii[NUM_COUNTRIES];
// 输入国家名称
for (int i = 0; i < NUM_COUNTRIES; i++) {
fgets(countries[i], sizeof(countries[i]), stdin);
countries[i][strlen(countries[i])-1] = '\0'; // 移除换行符
}
// 初始化指针数组
for (int i = 0; i < NUM_COUNTRIES; i++) {
ptr_arr_length[i] = countries[i];
ptr_arr_ascii[i] = countries[i];
}
// 按照长度排序并输出
sort_by_length(ptr_arr_length);
printf("Sort of Length:");
for (int i = 0; i < NUM_COUNTRIES; i++) {
printf("%s\n", ptr_arr_length[i]);
}
// 按照ASCII码排序并输出
sort_by_ascii(ptr_arr_ascii);
printf("Sort of ASCII:");
for (int i = 0; i < NUM_COUNTRIES; i++) {
printf("%s\n", ptr_arr_ascii[i]);
}
return 0;
}