文章
454
粉丝
0
获赞
1
访问
10.5k
把一行字符串中每个单词的首字母改成大写。单词之间用空格、制表、回车、换行等空白符分隔。
用一个布尔量 start 记录「当前位置是否处在单词开头」,初始为真。
遇到空白符把 start 置真;遇到非空白且 start 为真、字符是小写字母时改成大写,然后 start 置假。
原样输出其余字符,包括空白符的数量与位置。
O(L) 每行。
C:
#include <stdio.h>
#include <string.h>
int main(){
char s[300];
while(fgets(s, sizeof(s), stdin)){
int n=(int)strlen(s), i, start=1;
for(i=0;i<n;i++){
char c=s[i];
if(c==' '||c=='\t'||c=='\r'||c=='\n'||c=='\f'||c=='\v'){ start=1; }
else{
if(start && c>='a'&&c<='z') s[i]=c-'a'+'A';
start=0;
}
}
fputs(s, stdout);
if(n>0 && s[n-1]!='\n') printf("\n");
}
return 0;
}
C++:
#include <stdio.h>
#include <string.h>
int main(){
char s[300];
while(fgets(s, sizeof(s), stdin)){
int n=(int)strlen(s), i, start=1;
for(i=0;i<n;i++){
char c=s[i];
if(c==' ...
登录后发布评论
暂无评论,来抢沙发