[英]How to change the first letter of each word from lowercase to uppercase without using arrays in C?
我下面的代碼將文本的整個字母轉換為大寫字母。 但是,我需要在不使用 arrays、function 等的情況下將文件中的每個單詞大寫。使用 ASCII。
詩.txt:
The house cat sits
And smiles and sings
He knows a lot
Of secret things
我的代碼:
#include <stdio.h>
int main()
{
FILE *input;
FILE *output;
input = fopen ("poem.txt", "r");
output = fopen ("poem_modified.txt", "w");
if (input == NULL || output == NULL)
{
printf("Problem! \n");
return 1;
}
int ch;
while((ch=getc(input)) != EOF)
{
if( ch >= 'a' && ch <= 'z' )
{
ch = ch - 32;
}
fprintf(output, "%c", ch);
}
fclose(input);
fclose(output);
}
我會這樣做:
#include <stdio.h>
#include <stdlib.h>
#define ASCII_LOWER(c) ((c) >= 'a' && (c) <= 'z')
#define WHITESPACE(c) ((c) == ' ' || (c) == '\t' || (c) == '\n')
int main (void)
{
const char *ifname = "poem.txt";
const char *ofname = "poem_modified.txt";
FILE *ifp, *ofp;
int prevch = ' ', ch;
if ((ifp = fopen(ifname, "r")) == NULL) {
fprintf(stderr, "Cannot open the file '%s'\n", ifname);
return EXIT_FAILURE;
} else if ((ofp = fopen(ofname, "w")) == NULL) {
fclose(ifp);
fprintf(stderr, "Cannot open the file '%s'\n", ofname);
return EXIT_FAILURE;
}
while ((ch = fgetc(ifp)) != EOF) {
if (ASCII_LOWER(ch) && WHITESPACE(prevch))
ch += 'A' - 'a';
fputc(ch, ofp);
prevch = ch;
}
fclose(ifp);
fclose(ofp);
return 0;
}
不能被整個fgetc()
schmozzle 所困擾...這一次從字符的編譯時數組中模擬一個字符(這與隱藏數組fgetc()
使用的完全相同...
int main() {
char str[] =
"The house cat sits\n\n"
"And smiles and sings\n\n"
"He knows a lot\n\n"
"Of secret things\n" ;
bool inw = false;
for( int i = 0; str[i]; i++ ) {
char c = str[i]; // here is 'fgetc()'
if( ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') ) {
if( inw == false && c >= 'a' )
c -= 'a' - 'A';
inw = true;
} else inw = false;
putchar( c );
}
return 0;
}
#include <stdio.h>
int main()
{
FILE *input;
FILE *output;
input = fopen("poem.txt", "r");
output = fopen("poem_modified.txt", "w");
if (input == NULL || output == NULL)
{
printf("Problem! \n");
return 1;
}
int ch, track = 0;
while ((ch = getc(input)) != EOF)
{
if (track == 0)
{
ch &= ~(1 << 5);
track = -1;
}
if (ch == ' ')
track = 0;
fprintf(output, "%c", ch);
}
fclose(input);
fclose(output);
}
有一種簡單的方法可以將小寫字母轉換為大寫字母。 如果您仔細注意每個小寫和大寫字母的 ASCII 值,您會知道第五位設置為小寫。
一個 -> 1000001一個 -> 1100001
而且,所以我們只需要設置第五位。 (1<<5) 給出了一個數字,其第五位未設置,而 ~(1<<5) 的否定給出了一個僅設置了位的數字。 如果我們對字母執行按位和 (&) 操作,那么我們將得到大寫字母。 我已經初始化了一個變量名稱track = 0,並且在開始時它將第一個字母轉換為大寫並將其更改為-1。 每當我們得到一個空格('')時,將軌道更改為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.