C语言——经典200道实例(56-60)

56.使用 strcat() 连接两个字符串

#include <stdio.h>
int main()
{
    char s1[100], s2[100], i, j;
 
    printf("输入第一个字符串: ");
    scanf("%s", s1);
 
    printf("输入第二个字符串: ");
    scanf("%s", s2);
 
    // 计算字符串 s1 长度
    for(i = 0; s1[i] != '\0'; ++i);
 
    for(j = 0; s2[j] != '\0'; ++j, ++i)
    {
        s1[i] = s2[j];
    }
 
    s1[i] = '\0';
    printf("连接后: %s", s1);
 
    return 0;
}

 57. 计算字符串长度

         (1)使用 strlen()

 

#include <stdio.h>
#include <string.h>
 
int main()
{
    char s[1000];
    int len;
 
    printf("输入字符串: ");
    scanf("%s", s);
    len = strlen(s);
 
    printf("字符串长度: %d", len);
    return 0;
}

 58.查找字符在字符串中出现的次数

查找字符在字符串中的起始位置(索引值从 0 开始) 

#include <stdio.h>
 
int main()
{
   char str[1000], ch;
   int i, frequency = 0;
 
   printf("输入字符串: ");
   fgets(str, (sizeof str / sizeof str[0]), stdin);
 
   printf("输入要查找的字符: ");
   scanf("%c",&ch);
 
   for(i = 0; str[i] != '\0'; ++i)
   {
       if(ch == str[i])
           ++frequency;
   }
 
   printf("字符 %c 在字符串中出现的次数为 %d", ch, frequency);
 
   return 0;
}

 59.字符串中各种字符计算

计算字符串中的元音、辅音、数字、空白符 


#include <stdio.h>
 
int main()
{
    char line[150];
    int i, vowels, consonants, digits, spaces;
 
    vowels =  consonants = digits = spaces = 0;
 
    printf("输入一个字符串: ");
    scanf("%[^\n]", line);
 
    for(i=0; line[i]!='\0'; ++i)
    {
        if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
           line[i]=='o' || line[i]=='u' || line[i]=='A' ||
           line[i]=='E' || line[i]=='I' || line[i]=='O' ||
           line[i]=='U')
        {
            ++vowels;
        }
        else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
        {
            ++consonants;
        }
        else if(line[i]>='0' && line[i]<='9')
        {
            ++digits;
        }
        else if (line[i]==' ')
        {
            ++spaces;
        }
    }
 
    printf("元音: %d",vowels);
    printf("\n辅音: %d",consonants);
    printf("\n数字: %d",digits);
    printf("\n空白符: %d", spaces);
 
    return 0;
}

 60.字符串复制

    (1)使用 strcpy() 

#include <stdio.h>
#include <string.h>
 
int main()
{
   char src[40];
   char dest[100];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is runoob.com");
   strcpy(dest, src);
 
   printf("最终的目标字符串: %s\n", dest);
   
   return(0);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值