Yêu cầu: Viết chương trình đổi kí tự đầu tiên của mỗi từ thành chữ in hoa
Thuật toán:
- Tìm kí tự đầu tiên của một từ
- Kiểm tra xem kí tự có phải kí tự in thường. Sau đó, thay thế bằng kí tự in hoa (c = c – 32)
Code:
/**************Replace lowcase to uppercase character**********/
#include "stdio.h"
#include "conio.h"
#include "string.h"
void replowcase(char *str);
void main()
{
char str[] = " c programming at ngo ton blog ";
char c = '+';
printf("original string: '%s'\n", str);
replowcase(str);
printf("new string: '%s'\n", str);
getch();
}
/************************************************
Replace first character of each word into uppercase
*************************************************/
void replowcase(char *str)
{
int length = strlen(str);
int i;
bool isSpace = false;
for (i = 0; i < length; i++)
{
// the first character of string
if (i == 0 && str[i] != ' ' && str[i] != '\t')
{
if (str[i] <= 'z' && str[i] >= 'a')
{
str[i] = str[i] - 32;
}
}
if (str[i] == ' ' || str[i] == '\t')
{
isSpace = true;
}
else if (isSpace)
{
if (str[i] <= 'z' && str[i] >= 'a')
{
str[i] = str[i] - 32;
}
isSpace = false;
}
}
}
Kết quả:
1 2 |
original string: ' c programming at ngo ton blog ' new string: ' C Programming At Ngo Ton Blog ' |
Leave a Reply