12.14 按照字符串长度的大小来输出字符串,两种方法

发布于 2024-12-14  78 次阅读


#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int find(int* len, int n) {
    int max = -1;
    for (int i = 0; i < n; i++) {
        if (len[i] > max) {
            max = len[i];
       }
    }
    return max;
}

int main() {
    int n;
    scanf("%d", &n);
    getchar();
    char** str = malloc(sizeof(char*) * n);
    for (int i = 0; i < n; i++) {
        str[i] = malloc(sizeof(char) * 100);
    }
    for (int i = 0; i < n; i++) {
        gets(str[i]);
    }
    int* len = malloc(sizeof(int) * n);
    for (int i = 0; i < n; i++) {
        len[i] = strlen(str[i]);
    }
    int max = find(len, n);
    for (int i = 0; i < n; i++) {
        if (len[i] == max) {
            printf("%s", str[i]);
        }
    }
    return 0;
}

第二种方法,直接对这三个字符串进行排序

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>

int main() {
	char str[3][100];
	for (int i = 0; i < 3; i++) {
		fgets(str[i], sizeof(str[i]), stdin);
		str[i][strcspn(str[i], "\n")] = 0;
	}
	int len[3];
	for (int i = 0; i < 3; i++) {
		len[i] = strlen(str[i]);
	}
	//开始排序
	for (int i = 0; i < 3; i++) {
		int maxlen = len[i];
		int t = 0;
		for (int j = i + 1; j < 3; j++) {
			if (maxlen < len[j]) {
				maxlen = len[j];
				t = j;
			}
		}
		//这里的maxlen的作用只是为了添加标志,真正有用的j,即最大的字符串str[下标]
		if (maxlen != len[i]) {
			//交换长度,这是必要的!
			int le=len[i];
			len[i] = len[t];
			len[t] = le;
			char s[100];
			//要交换的是str[i]和str[t]
			strcpy(s, str[i]);
			strcpy(str[i], str[t]);
			strcpy(str[t], s);
		}
	}
	for (int i = 0; i < 3; i++) {
		printf("%s\n", str[i]);
	}
	return 0;
}

交换字符串的同时也要交换对应的len值,因为我们是靠len的值来比较的

届ける言葉を今は育ててる
最后更新于 2024-12-17