在我的代碼中,我使用了一個 tolower 函式來消除不考慮大小寫的字母。(不區分大小寫)但我的問題是,如果我的第一個輸入是“HELLO”而我的第二個是“hi”,則輸出將是小寫字母的“ello”而不是“ELLO”。有沒有什么辦法解決這一問題?我不應該使用 tolower 函式嗎?
#include <stdio.h>
#include <conio.h>
void main()
{
char s1[20],s2[20];
int i,j;
printf("\nEnter string 1:- ");
gets(s1);
printf("\nEnter the string for matching:- ");
gets(s2);
for(int i = 0; s1[i]; i )
{
s1[i] = tolower(s1[i]);
}
for(int i = 0; s2[i]; i )
{
s2[i] = tolower(s2[i]);
}
for (i=0;(i<20&&s1[i]!='\0');i )
{
for (j=0;(j<20&&s2[j]!='\0');j )
{
if (s1[i]==s2[j])
s1[i]=' ';
}
}
printf("\nString 1 after deletion process is %s",s1);
printf("\nIts compressed form is ");
for (i=0;(i<20&&s1[i]!='\0');i )
{
if (s1[i]!=' ')
printf("%c",s1[i]);
}
getch();
}
uj5u.com熱心網友回復:
- 寫一個函式
- 直接比較 tolower() 的結果——不要改變字串本身
- 不要使用
gets()和scanf("%s")——兩者都沒有邊界檢查
編輯:抱歉,這個函式只是比較兩個字串。它旨在讓您了解如何tolower()有效使用,而不是為您完成作業。:-)
#include <iso646.h>
#include <ctype.h>
bool is_equal( const char * a, const char * b )
{
while (*a and *b)
{
if (tolower( *a ) != tolower( *b ))
return false;
a;
b;
}
if (*a or *b) return false;
return true;
}
現在您可以直接呼叫該函式。
if (is_equal( "HELLO", "hello" )) ...
在 C 中從用戶那里獲取字串輸入總是很痛苦,但您可以使用fgets()它。
char s[100]; // the target string (array)
fgets( s, 100, stdin ); // get max 99 characters with null terminator
char * p = strchr( s, '\n' ); // find the Enter key press
if (p) *p = '\0'; // and remove it
puts( s ); // print the string obtained from user
您總是可以將所有煩人的東西包裝起來,以便將字串放入一個函式中。
uj5u.com熱心網友回復:
有沒有什么辦法解決這一問題?我不應該使用 tolower 函式嗎?
而不是更改s1[]為小寫,保留s1[]“原樣”并更改比較。還是好改s2[]。
// if (s1[i]==s2[j]) s1[i]=' ';
if (tolower(((unsigned char*)s1)[i]) == s2[j]) s1[i]=' ';
tolower(int ch)int對unsigned char范圍 和中的所有值進行了明確定義EOF。由于 achar可能是負數并且字串處理最好按 完成unsigned char,因此請使用強制轉換。也在s2[]加工中。
也不要使用gets(). 研究fgets()。
uj5u.com熱心網友回復:
您的代碼存在安全漏洞,因為您正在使用gets()(如果用戶輸入的文本大于 19 位元組,則變數s1和將出現緩沖區溢位s2)。此功能有問題,無法修復,永遠不應使用。而是使用,例如,fgets(s1, sizeof(s1), stdin)。
問題的主要思想是您必須保留字串,因此洗掉修改它們的回圈。在這種情況下,用于檢查每個比較字符是否相同而不考慮大小寫的正確謂詞將變為:
if (tolower((unsigned char)s1[i]) == tolower((unsigned char)s2[j]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404676.html
標籤:
