[英]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;
記得隨身攜帶一份好的參考資料:
https://en.cppreference.com/w/c
一個非常好的,但非常技術。 需要一些時間來習慣閱讀它。
https://cplusplus.com/reference/
總是被人嗤之以鼻,但也不是那么糟糕。 對於初學者來說非常容易遵循。
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.