- C语言经典题目练习1
- 一、质因数
- 二、字符串子串
- 三、字符串连接
- 四、字符串排序
- 五、字符串字符统计
分解质因数的思路就是用该数n不断除以一个递增的数i(该数初始为2,递增至n)若能整除i,则当前i就为n的因子之一然后将n用该因子缩小即n=n/i再重复执行上述操作,若n = i则说明分解因子结束了。
int main(void)
{
int n = 0,i = 0;
printf("please input n:");
scanf("%d",&n);
printf("n = ");
for(i = 2 ; i<=n;i++)
{
if(n % i == 0)
{
n = n/i;
printf("%d * ",i);
}
}
printf("%dn",n);
}
二、字符串子串
求一个字符串中子串出现的次数譬如:
字符串:abcbchibcbchid
子串:bc
次数:4
#include三、字符串连接#include int subnumber(char *str1,char *str2) { int i = 0,j = 0,count = 0; for(i = 0;i for(j = 0;j if(str1[i+j] != str2[j]) { break; } } if(j == strlen(str2)) { count++; } } return count; } int main(void) { char str1[24] = {0}; char str2[24] = {0}; int ret = 0; printf("please input str1:"); scanf("%s",str1); printf("please input str2:"); scanf("%s",str2); ret = subnumber(str1,str2); printf("ret = %dn",ret); return 0; }
将两个字符串连在一起譬如:
str1:abc
str2:def
输出:abcdef
#include四、字符串排序#include char *LinkString(char *str1,char *str2) { char *string = NULL; string = str1; while(*str1 != ' ') { str1++; } while(*str1++ = *str2++); return string; } int main(void) { char str1[24] = {0}; char str2[24] = {0}; char *str = NULL; printf("pleasee input str1:"); scanf("%s",str1); printf("pleasee input str2:"); scanf("%s",str2); str = LinkString(str1,str2); printf("LinkString = %sn",str); return 0; }
将字符串进行排序按照ASCII排序
使用的strcmp和strcpy完成
如果返回值小于 0,则表示 str1 小于 str2
如果返回值大于 0,则表示 str2 大于 str1
如果返回值 = 0,则表示 str1 等于 str2
#include五、字符串字符统计#include void swap(char *str1,char *str2) { char temp[24] = {0}; strcpy(temp,str1); strcpy(str1,str2); strcpy(str2,temp); } int main(void) { char str1[24] = {0}; char str2[24] = {0}; char str3[24] = {0}; printf("please input str1:"); scanf("%s",str1); printf("please input str2:"); scanf("%s",str2); printf("please input str3:"); scanf("%s",str3); printf("---------------排序前--------------n"); printf("%sn",str1); printf("%sn",str2); printf("%sn",str3); printf("---------------排序后--------------n"); if(*str1 >= *str2) { swap(str1,str2); } if(*str2 >= *str3) { swap(str2,str3); } printf("%sn",str1); printf("%sn",str2); printf("%sn",str3); return 0; }
统计字符串中的字母、数字、空格和其他字符的个数
#include#include int main(void) { char ch = 0; int i = 0; int space = 0;//空格 int letter = 0;//字母 int number = 0;//数字 int others = 0;//其他 printf("please input str:"); while((ch = getchar()) != 'n') { //数字统计 if((ch >= '0') && (ch <= '9')) { number++; } //字母统计大小写 else if(((ch >= 'A') && (ch <= 'Z')) ||((ch >= 'a') &&(ch <= 'z'))) { letter++; } //空格 else if(ch == ' ') { space++; } //其他字符 else { others++; } } printf("number = %dn",number); printf("letter = %dn",letter); printf("space = %dn",space); printf("others = %dn",others); return 0; }



