您的位置:首页 > 编程语言 > C语言/C++

C语言字符串练习1

2009-07-23 18:31 375 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: