C语言字符串练习1

1.演示字符串的输入输出。

#include<stdio.h>

void main()
{
 char name[30],dept[20];

 printf("/n 请输入姓名:");
 gets(name);//获取键盘上输入的一串字符。
 printf("/n 请输入部门:");
 gets(dept);
 printf("/n 雇员姓名是:");
 puts(name);//显示键盘上输入的一串字符。
 printf("/n 雇员部门是:");
 puts(dept);
}

 

 

2.统计一行字符中的空格数。

#include<stdio.h>

void main()
{
 char line[30];
 int i,count=0;
 printf("/n 请输入一行字符:");
 gets(line);
 i=0;
 while(line[i]!='/0')
 {
  if(line[i]==' ')
  {
   count++;
  }
  i++;
 }
 printf("/n 这行字符的空格数是:%d /n",count);
}

 

 

3.字符串处理函数strlen()检查字符长度函数。

#include<stdio.h>
#include<string.h>

void main()
{
 char arr[]="Beijing";
 int len1,len2;
 len1=strlen(arr);
 len2=strlen("Shanghai");
 printf("/n string=%s  length=%d",arr,len1);
 printf("/n string=%s  length=%d/n","Shanghai",len2);
}

 

 

4.函数strcpy()将一个字符串复制到另一个字符串的函数。

#include<stdio.h>
#include<string.h>

void main()
{
 char source[]="we chang lives";
 char target[20];
 strcpy(target,source);
 printf("/n 源字符串=%s/n",source);
 printf("/n 目标字符串=%s/n",target);
}

 

5.比较两个字符串的函数strcmp()。

#include<stdio.h>
#include<string.h>

void main()
{
 char username[15],pwd[15];
 printf("/n 请输入用户名:");
 gets(username);
 printf("/n 请输入密码:");
 gets(pwd);
 if((strcmp(username,"John")==0)&&(strcmp(pwd,"123456")==0))//比较字符串时区分大小写的。
 {
  printf("/n 您已成功登录!/n");
 }
 else
 {
  printf("/n 用户名或密码错误!/n");
 }
}

 

 

6.连接两个字符串的函数strcat()。

#include<stdio.h>
#include<string.h>

void main()
{
 char source_string[]=" is very good";
 char target_string[30]="Accp 5.0";
 strcat(target_string,source_string);
 printf("/n 源字符串=%s",source_string);
 printf("/n 目标字符串=%s/n",target_string);
}

 

7.指针和字符串演示,统计字符串里字符a的个数。

#include<stdio.h>
#include<string.h>

void main()
{
 char username[30]="wahaha yiyiyaya";
 char *p;
 int count=0;
 for(p=username;*p!='/0';p++)
 {
  if(*p=='a')
  {
   count++;
  }
 }
 printf("/n字符a的个数为:%d/n",count);
}

 

8.字符指针数组会使对字符串的操作变得更容易。以下是通过地址交换操作进行值变换。

#include<stdio.h> 

void main()
{
 char *names[]={"Apple","Pear","Banana","Peach"};
 char *temp;
 printf("/n 第二个和第三个元素名称分别为:%s %s",names[1],names[2]);
 //对第二个和第三个元素进行交换。
 temp=names[1];
 names[1]=names[2];
 names[2]=temp;
 printf("/n 第二个和第三个元素交换后分别为:%s %s/n",names[1],names[2]);
}

 

 

9.用于接收用户输入的城市,并在城市输入的值为"New York"时显示消息“您来自纽约,我也是”,否则显示“我们居住在不同的城市”。

#include<stdio.h>
#include<string.h>

void main()
{
 char cityname[25];
 printf("/n 请输入你居住的城市:");
 gets(cityname);
 if(strcmp(cityname,"New York")==0)
  printf("/n 您来自纽约,我也是/n");
 else
  printf("/n 我们居住在不同的城市/n");
}

 

10.统计输入字符串中的字符“x”出现的次数。

#include<stdio.h>
#include<string.h>

void main()
{
 char inputstring[30];
 char *p;
 int count=0;
 printf("/n 请输入一行字符串:");
 gets(inputstring);
 for(p=inputstring;*p!='/0';p++)
 {
  if(*p=='x')
  {
   count++;
  }
 }
 printf("/n字符x的个数为:%d/n",count);
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值