第九次隨筆
- 用迴圈結構,求字串長度
#include<stdio.h>
main()
{
char str[80];
int cnt[10]={0};
int i=0;
gets(str);
while(str[i]!='\0')
{
if(str[i]>='0'&&str[i]<='9')
cnt[(str[i]-'0')%10]++;
i++;
}
for(i=0;i<=9;i++)
printf("數字字元%d:%d個\n",i,cnt[i]);
}
- 編寫程式,統計字串大寫字母的個數。
#include<stdio.h>
main()
{
char str[20];
int i,cnt;
cnt=i=0;
gets(str);
while(str[i]!='\0')
{
if(str[i]>='A'&&str[i]<='Z')
cnt++;
i++;
}
printf("大寫字母個數為:%d\n",cnt);
}
- 編寫程式,去掉字串中所有的星號,例如****ab
**c***de**fg***整理成abcdedg
#include<stdio.h>
main()
{
char str[20];
int i,j;
i=j=0;
gets(str);
while(str[i]!='\0')
{
if(str[i]!='*')
str[j++]=str[i];
i++;
}
i=0;
while(i<j)
putchar(str[i++]);
}
- 編寫程式,將字元陣列a中的字母複製到字元陣列b中,要求每三個字元後插入一個空格,例如,字元陣列a:abcdefghijk,字元b:abc def ghi jk。
#include<stdio.h>
main()
{
char a[20],b[20];
int i,j;
gets(a);
for(i=j=0;a[i]!='\0';i++)
{
b[j++]=a[i];
if((i+1)%3==0)
b[j++]=' ';
}
b[j]='\0';
puts(b);
}
5.輸入字串中位置為奇數,ASCII為偶數的字元。
#include<stdio.h>
main()
{
char str[80];
int i=0;
gets(str);
while(str[i]!='\0')
{
if((i+1)%2==1&&str[i]%2==0)
putchar(str[i]);
i++;
}
}