字符串比较和长度

时间:2014-10-20 13:45:40

标签: c string comparison string-length

嗨,我正在尝试修改一个程序,但是我遇到了很多困难。该计划是我自己组成的挑战。我想从用户那里读取6个字符串。然后我想创建一个函数,允许我比较这些字符串,找出哪个字符串大小不同。然后我想将此信息传递给另一个函数,该函数将确定不同字符串的字符串长度。最后打印出值。这是我到目前为止所做的(许多错误)。

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

char* diffFun(char* ,char*,char * ,char *,char * ,char *)
    {
    char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;
    char *s6;
    char *result;
    if (strcmp(s2,s3,s4,s5,s6)<strcmp(s1))
            result =  s1;
    else if (strcmp(s1,s3,s4,s5,s6)<strcmp(s2))
            result s2;
    return result;
    }

int main()
    {
    char *str1;
    char *str2;
    char *str3;
    char *str4;
    char *str5;
    char *str6;

    printf("Give me a string1:\n");
    str1 = readString(stdin);
    printf("Give me a string2:\n");
    str2 = readString(stdin);
    printf("Give me a string3:\n");
    str3 = readString(stdin);
    printf("Give me a string4:\n");
    str4 = readString(stdin);
    printf("Give me a string5:\n");
    str5 = readString(stdin);
    printf("Give me a string6:\n");
    str6 = readString(stdin);

    char *cond;
    cond = diffFun((char* str1,char* str2,char* str3,char* str4,char* str5,char* str6);
    printf("%ls",cond);

    return 0;
    }

1 个答案:

答案 0 :(得分:0)

我不太了解,但我觉得如下......

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

char* diffFun(int n, char *s[n]){
    int i, j;
    char *result = s[0];
    size_t result_len = strlen(result);

    for(i = 1; i < n; ++i){
        size_t len = strlen(s[i]);
        if(result_len < len){
            result = s[i];
            result_len = len;
        } else if(result_len == len && strcmp(result, s[i]) < 0){
            result = s[i];
        }
    }
    return result;
}

int main(void){
    char *str[6];
    int i;
    for(i=0;i<6; i++){
        printf("Give me a string%d:\n", i+1);
        str[i] = readString(stdin);
    }

    char *cond = diffFun(6, str);
    printf("%s",cond);

    return 0;
}