A. c語言從鍵盤上輸入一串字元 (不超過 80 個字元 ),直 到 回 車 結束。輸出其中數字字元的個數
可以參考下面的示例:
#include <stdio.h>
int main()
{
int i=0, space=0, num=0, n=0, ch=0;
char s[20];
printf("請輸入一串字元 ");
gets(s);
while(s[i] != '\0')
{
if(s[i]==' ')
space++;
else if(s[i]<='9' && s[i]>='0')
num++;
else if(s[i]<='z' && s[i]>='a' || s[i]<='Z' && s[i]>='A')
ch++;
else
n++;
i++;
}
printf("剛才輸入的字元中英文字元個數為 %d\n", ch);
printf("剛才輸入的字元中空格個數為 %d\n", space);
printf("剛才輸入的字元中數字個數為 %d\n", num);
printf("剛才輸入的字元中其他個數為 %d\n", n);
return 0;
}
B. C語言程序從鍵盤上輸入兩個字元串若不相等將短的字元串連接到長的字元串的末尾並
#include "stdio.h"
#include "string.h"
#define MAX 500
void main()
{
char str1[MAX], str2[MAX];
int len1, len2;
printf("input string 1 : ");
gets(str1); /* 輸入字元串1 */
printf("input string 2 : ");
gets(str2); /* 輸入字元串2 */
len1 = strlen(str1); /* 獲取字元串1的長度 */
len2 = strlen(str2); /* 獲取字元串2的長度 */
if(len1 < len2)
{
strcat(str2, str1); /* 將短的字元串1接在較長的字元串2的後面 */
printf("new string : %s ", str2);
}
else
{
strcat(str1, str2);
printf("new string : %s ", str1);
}
}
把
for(k=0;a[k]!=0;k++)
{
printf("%s",a[k]);
}
改成
for(k=0;a[k]!=0;k++)
{
printf("%c",a[k]);
}
(2)c語言從鍵盤輸入符串擴展閱讀:
C語言的字元串其實就是以'