根据升序字母顺序查找第一个和最后一个字符串单词

时间:2015-02-16 15:35:55

标签: c arrays

作为主题,要键入的单词数由用户决定。假设它是< = 10。我已经对我面临的错误代码做了一些评论,这导致字符串部分的比较显然不起作用。

int main()
{
    int size, i;
    char wordArray[10][20]; // buffer of 10 words of 20 length
    char first[20]; // buffer 20 length
    char last[20]; // buffer 20 length
    printf("Enter size: ");
    scanf("%d", &size);
    printf("Enter %d words separated by space: ", size);
    for (i = 0; i < size; i++)
    {
        scanf("%s", wordArray[i]);
    }
    findWord(wordArray, size, &first, &last);
}

void findWord(char word[][20], int size, char *first, char *last)
{
    *first = word[i]; // initialize to first element. 
    *last = word[i];
    printf("first = %s", first); // for debugging purposes I got some weird symbol as prefix before my first element of word. Why is it so?
    printf("last = %s", last);
    int i = 0;
    for (i = 0; i < size; i++)
    {
        if (strcmp(word[i], *first) > 1)
        {
            *last = *first;
            *first = word[i];
        }
        else if (strcmp(word[i], *last) < 1)
        {
            *last = word[i];
        }
    }
}

1 个答案:

答案 0 :(得分:0)

以下两种解决方案并不完全相同:

  • 通过参数传递指向char的指针。调用该函数后,first按字母顺序words[i][0]指向第一个。调用该函数后,如果words[i]被修改,first(看作一个字符串)也会改变。要编译:{{1​​}}

    gcc main.c -o main
  • 第二个解决方案:将#include<string.h> #include<stdio.h> void findWord(char word[][20], int size, char **first, char **last); int main() { int size, i; char wordArray[10][20]; // buffer of 10 words of 20 length // char first[20]; // buffer 20 length // char last[20]; // buffer 20 length char* first; char* last; printf("Enter size: "); scanf("%d", &size); printf("Enter %d words separated by space: ", size); for (i = 0; i < size; i++) { scanf("%s", wordArray[i]); } findWord(wordArray, size, &first, &last); printf("first = %s\n", first); printf("last = %s\n", last); } void findWord(char word[][20], int size, char **first, char **last) { int i = 0; *first = word[i]; // initialize to first element. *last = word[i]; for (i = 0; i < size; i++) { if (strcmp(word[i], *first) < 0) { // *last = *first; *first = word[i]; } else if (strcmp(word[i], *last) > 0) { *last = word[i]; } } } 声明为char(first数组并使用strcpy()复制字符串char first[20]。调用该函数后,如果{ {1}}已修改,words[i](视为字符串)将保持不变。

    words[i]

选择你的!