[英]C using tolower case-insensitive
在我的代码中,我使用了较低的 function 来消除不考虑大小写的字母。 (不区分大小写)但我的问题是,如果我的第一个输入是“HELLO”而我的第二个输入是“hi”,则输出将是小写字母的“ello”而不是“ELLO”。 有没有什么办法解决这一问题? 我不应该使用tolow function吗?
#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();
}
您的代码存在安全漏洞,因为您使用的是gets()
(如果用户输入的文本大于 19 个字节,您将在变量s1
和s2
上出现缓冲区溢出)。 这个 function 有问题,无法修复,永远不要使用。 而是使用例如fgets(s1, sizeof(s1), stdin)
。
问题的主要思想是您必须保留字符串,因此删除修改它们的循环。 在这种情况下,检查每个比较字符是否相同而不考虑大小写的正确谓词将变为:
if (tolower(s1[i]) == tolower(s2[j]))
gets()
和scanf("%s")
— 两者都没有边界检查编辑:对不起,这个 function 只是比较两个字符串。 它旨在让您了解如何有效地使用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;
}
if (*a or *b) return false;
return true;
}
现在您可以直接调用 function。
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
您总是可以将所有用于获取字符串的烦人的东西包装到 function 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.