[英]Converting Mixed Character C String to Lower Case
I am running into a wall here because I don't see how I can iterate over the string and use the tolower() function without severely breaking my dynamically allocating array.我在这里碰壁了,因为我看不到如何遍历字符串并使用 tolower() function 而不会严重破坏我的动态分配数组。 Any advice would be suggested.将提出任何建议。
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;
}
It is helpful to have a utility function to lowercase/uppercase/titlecase/whatever you want to do to your string, such as:将实用程序 function 用于小写/大写/标题/您想对字符串执行的任何操作都会很有帮助,例如:
#include <ctype.h>
char * lowercase( char * s )
{
for (char * p = s; *p; ++p)
{
*p = tolower( *p );
}
return s;
}
Now, since your data is an array of strings , just use the function on each string in your data.现在,由于您的数据是一个字符串数组,因此只需在数据中的每个字符串上使用 function 即可。 With the function defined as it is above, you can do it in-line with your copy:使用上面定义的 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;
Remember to keep a good reference handy:记得随身携带一份好的参考资料:
https://en.cppreference.com/w/c https://en.cppreference.com/w/c
A very good one, but very technical.一个非常好的,但非常技术。 Takes some time to get used to reading it.需要一些时间来习惯阅读它。
https://cplusplus.com/reference/ https://cplusplus.com/reference/
Gets pooh-poohed all the time, but isn't all that bad.总是被人嗤之以鼻,但也不是那么糟糕。 Very much easier for the beginner to follow.对于初学者来说非常容易遵循。
alternative without using tolower library
If you want to convert a word from upper case to lower case, you can use the ASCII table.如果要将单词从大写转换为小写,可以使用 ASCII 表。
Here my program to convert it !这里我的程序来转换它!
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.