繁体   English   中英

将混合字符 C 字符串转换为小写

[英]Converting Mixed Character C String to Lower Case

我在这里碰壁了,因为我看不到如何遍历字符串并使用 tolower() function 而不会严重破坏我的动态分配数组。 将提出任何建议。

while (fscanf(file, "%s", str) != EOF) { 
    //doubles the word_alloc/str_array if we have more words than allocated
    if(ThreadData.word_count >= ThreadData.word_alloc) {
        ThreadData.word_alloc *= 2;
        ThreadData.str_array =(char **) realloc(ThreadData.str_array, sizeof(char*) * ThreadData.word_alloc);
    }       
    ThreadData.str_array[ThreadData.word_count] = (char *) malloc(sizeof(char) * (strlen(str) + 1));
    strcpy(ThreadData.str_array[ThreadData.word_count], str);
    ++ThreadData.word_count;
}

将实用程序 function 用于小写/大写/标题/您想对字符串执行的任何操作都会很有帮助,例如:

#include <ctype.h>

char * lowercase( char * s )
{
  for (char * p = s;  *p;  ++p)
  {
    *p = tolower( *p );
  }
  return s;
}

现在,由于您的数据是一个字符串数组,因此只需在数据中的每个字符串上使用 function 即可。 使用上面定义的 function ,您可以在您的副本中执行此操作:

ThreadData.str_array[ThreadData.word_count] = (char *) malloc(sizeof(char) * (strlen(str) + 1));
lowercase(strcpy(ThreadData.str_array[ThreadData.word_count], str));
++ThreadData.word_count;

记得随身携带一份好的参考资料:

alternative without using tolower library

如果要将单词从大写转换为小写,可以使用 ASCII 表。

这里我的程序来转换它!

main.h

#ifndef _HEADER_H_
#define _HEADER_H_

void fill_str(char*);
void convert_to_lower_case(char*);

#endif

main.c

#include <stdio.h>
#include <stdlib.h>
#include "main.h"

int main(){
    int size = 15; // Size of your string
    char* str = (char*) malloc(sizeof(char) * size);
    fill_str(str);
    convert_to_lower_case(str);
    printf("%s", str);
    return 0;
}

void fill_str(char* str){
    printf("Enter your word : ");
    scanf("%s", str);
}

void convert_to_lower_case(char* str){
    int i = 0;
    while(str[i] != '\0'){
        if( (int)str[i] >= 65 && (int)str[i] <= 90){ // We are verifying if the ascii code of a character is in upper case
            int ascii = str[i] + 32; // Example: ASCII code of "A" => 65 and "a" => 97. So 97 - 65 = 32;
            str[i] = (char) ascii;
        }
        i++;
    }
}

暂无
暂无

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

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