繁体   English   中英

C中的lower功能不允许我转换字符串

[英]The function tolower in C does not allow me to convert a string

考试文字说

程序应以不区分大小写的方式执行,例如“ How”和“ hoW”是同一个词

所以我创建了一个字符,使用atoi将其传递给一个值,然后尝试将其所有内容都转换为小写。

例:

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

#define STR_LEN 20 

int main(int argc, char *argv[])
{

    if(argc != 3) {
        fprintf(stderr, "Incorrect number of arguments.\n");
        exit(EXIT_FAILURE);
    }

    char word1[STR_LEN +1];
    strcpy(word1, argv[1]);

    int i;
    for(i=0;i<strlen(word1);i++){
    word1 = tolower(word1[i]);
    }

    char word2[STR_LEN +1];
    strcpy(word2, argv[2]);

    FILE *fin;
    fin = fopen("MyTEXTFile.TXT", "r");
    if(fin == NULL) {
        fprintf(stderr, "Can't open the file.\n");
        exit(EXIT_FAILURE);
    }

    char w1[STR_LEN +1] = "";
    char w2[STR_LEN +1];
    int found = 0;

    while(fscanf(fin, "%s", w2) != EOF) {
        printf("DEBUG: Checking \"%s\" \"%s\"\n", w1, w2);

        if(strcmp(w1, word1)==0 && strcmp(w2, word2)==0) {
            ++found;
        }
        if(strcmp(w1, word2)==0 && strcmp(w2, word1)==0) {
            ++found;
        }

        strcpy(w1, w2);
    }
    fclose(fin);

    if(found > 0) {
        printf("The words \"%s\" and \"%s\" appear consecutively in the text %d times", word1, word2, found);
    } else {
        printf("The words \"%s\" and \"%s\" never appear consecutively in the text", word1, word2);
    }

    return EXIT_SUCCESS;
}

为什么程序在这里给我一个错误:

 int i;
 for(i=0;i<strlen(word1);i++){
   word1 = tolower(word1[i]);
 }

将所有的字母都转换为小写字母应该怎么做?

改成 :

int i;
for(i=0;i<strlen(word1);i++){
    word1[i] = tolower(word1[i]);
}

在代码中,您将word1的字符分配给字符串指针,这很糟糕

tolower的手册页。 该函数一次仅转换一个字符。 您必须遍历所有字符串并使用word1 [i]转换一个字符。 如果只需strcasecmp区分大小写的比较,则可以使用strcasecmp

int i;

for (i=0; i<strlen(word1); i++)
    word1[i] = tolower(word1[i]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM