Yêu cầu: Kiểm tra tính đối xứng của chuỗi
Ví dụ: “NGOTON”: là chuỗi không đối xứng, “RADAR” là chuỗi đối xứng.
Thuật toán:
Lần lượt so sánh các cặp kí tự của chuỗi nếu khác return false
Code:
/***************Check string is symmetry***********************/
#include "stdio.h"
#include "conio.h"
#include "string.h"bool isSymStr(const char *str);
void main()
{
char str1[] = "ngoton.it";
char str2[] = "RADAR";
printf("'%s' is symmetry: %s\n", str1, isSymStr(str1)? "TRUE" : "FALSE");
printf("'%s' is symmetry: %s\n", str2, isSymStr(str2)? "TRUE" : "FALSE");
getch();
}
/************************************************
Check whether string is symmetry or not?
- if symmetry, return true
- if not, return false
*************************************************/
bool isSymStr(const char *str)
{
int i, len = strlen(str);
bool re = true;
for (i = 0; i < len/2; i++)
{
if (str[i] != str[len-i-1])
{
re = false;
break;
}
}
return re;
}
Kết quả:
1 2 |
'ngoton.it' is symmetry: FALSE 'RADAR' is symmetry: TRUE |
Leave a Reply