C语言 我可以添加什么字符串函数而不是一些代码序列?



在这个程序中,我必须使用尽可能多的字符串函数。我用的是粗棉布。我可以添加什么其他字符串函数而不是一些代码序列?我尝试添加strmp来比较,但没有成功。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
bool palindrom(char str[])
{
int l = 0, h = strlen(str) - 1;
for (int i = 0; i <= h; i++)
str[i] = tolower(str[i]);
while (l <= h) {
if (!(str[l] >= 'a' && str[l] <= 'z'))
l++;
else if (!(str[h] >= 'a' && str[h] <= 'z'))
h--;
else if (str[l] == str[h])
l++, h--;
else
return false;
}
return true;
}
int main()
{
char str[100];
printf("Introduceti sirul : ");
scanf("%[^n]",str);
if (palindrom(str))
printf("Propozitia este palindrom.");
else
printf("Propozitia nu este palindrom.");
return 0;
}

两个建议:

  • fgets读取字符串。
    • 子建议:iscntrl检查字符串
    • 中的控制字符,如换行符
  • puts打印末尾应该有换行符的字符串。
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
bool palindrom(char str[]) {
// Convert to lowercase and get a pointer to the end in one go.
// (You don't actually need the string length)
// Note: You should convert to unsigned char before using ctype.h functions:
char* end = str;
for(;!iscntrl((unsigned char)*end); ++end) {
*end = tolower((unsigned char)*end);
}
// terminate at the first control char which is probably newline
// you get when using `fgets`:
*end = '';
// loop until the pointers meet:
for(; str < end--; ++str) {
// return false if they are not pointing at equal letters:
if(*str != *end) return false;
}
return true;
}
int main() {
char str[100];
printf("Introduceti sirul : ");
// Use fgets:
if(fgets(str, sizeof str, stdin)) {
if(palindrom(str))
puts("Propozitia este palindrom.");    // use puts
else
puts("Propozitia nu este palindrom."); // use puts
}
}

最新更新