C/C++ 寻找最小字符串:输入多个字符串并使用函数查找
#include <stdio.h> #include <string.h>
void find(char *name[], int n, int *p);
int main() { char s[7]; char *str[100]; int cnt = 0; // 输入多个字符串,以'####'为结束标记 while (scanf('%s', s) == 1 && strcmp(s, '####') != 0) { // 动态分配内存存储字符串 str[cnt] = (char *) malloc(sizeof(char) * 7); strcpy(str[cnt], s); cnt++; } int index; find(str, cnt, &index); // 查找最小的字符串 printf('%s\n', str[index]); // 输出最小的字符串 // 释放动态分配的内存 for (int i = 0; i < cnt; i++) { free(str[i]); } return 0; }
void find(char *name[], int n, int *p) { *p = 0; // 初始化最小字符串下标为0 for (int i = 1; i < n; i++) { if (strcmp(name[i], name[*p]) < 0) { // 如果第i个字符串比当前最小字符串小,更新最小字符串下标 *p = i; } } }
原文地址: https://www.cveoy.top/t/topic/ojKR 著作权归作者所有。请勿转载和采集!