温馨提示×

c语言怎么输出最短字符串

小亿
82
2024-09-05 06:20:44
栏目: 编程语言

在C语言中,要输出最短的字符串,首先需要定义一个函数来判断两个字符串哪个更短。然后使用printf()函数将较短的字符串输出到控制台。以下是一个示例代码:

#include<stdio.h>
#include<string.h>

// 函数原型声明
const char* find_shortest_string(const char* str1, const char* str2);

int main() {
    const char* str1 = "Hello";
    const char* str2 = "World!";
    
    const char* shortest_string = find_shortest_string(str1, str2);
    printf("The shortest string is: %s\n", shortest_string);

    return 0;
}

// 函数实现
const char* find_shortest_string(const char* str1, const char* str2) {
    if (strlen(str1) < strlen(str2)) {
        return str1;
    } else {
        return str2;
    }
}

这个程序首先定义了一个名为find_shortest_string的函数,该函数接收两个字符串参数,并返回较短的字符串。在main函数中,我们调用这个函数并将结果存储在shortest_string变量中。然后使用printf()函数将最短的字符串输出到控制台。

0