Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3897015
  • 博文数量: 408
  • 博客积分: 10227
  • 博客等级: 上将
  • 技术积分: 9820
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-17 21:48
个人简介

非淡泊无以明志,非宁静无以致远

文章存档

2022年(1)

2021年(1)

2020年(2)

2019年(5)

2018年(4)

2017年(3)

2016年(24)

2015年(8)

2014年(7)

2013年(3)

2012年(1)

2011年(23)

2010年(179)

2009年(147)

分类: C/C++

2010-01-07 23:11:58

1.字符串整体拷贝 :

原型strcpy(char destination[], const char source[]);

功能将字符串source拷贝到字符串destination

例程

#include

#include

void main(void)

{

  char str1[10] = { "TsinghuaOK"};

  char str2[10] = { "Computer"};

  cout <

}

运行结果是:Computer

第二个字符串将覆盖掉第一个字符串的所有内容!

注意:在定义数组时,字符数组1的字符串长度必须大于或等于字符串2的字符串长度。不能用赋值语句将一个字符串常量或字符数组直接赋给一个字符数组。所有字符串处理函数都包含在头文件string.h中。

2.字符串部分拷贝 :

原型strncpy(char destination[], const char source[], int numchars);

功能将字符串source中前numchars个字符拷贝到字符串destination

例程

#include

#include

void main(void)

{

  char str1[10] = { "Tsinghua "};

  char str2[10] = { "Computer"};

  cout <

}

运行结果:Comnghua

注意:字符串source中前numchars个字符将覆盖掉字符串destination中前numchars个字符!

3.字符串整体连接字符:

原型:strcat(char target[], const char source[]);

功能:将字符串source接到字符串target的后面

例程:

#include

#include

void main(void)

{

  char str1[] = { "Tsinghua "};

  char str2[] = { "Computer"};

  cout <

}

运行结果:Tsinghua Computer

注意:在定义字符数组1的长度时应该考虑字符数组2的长度,因为连接后新字符串的长度为两个字符串长度之和。进行字符串连接后,字符串1的结尾符将自动被去掉,在结尾串末尾保留新字符串后面一个结尾符。

4.字符串部分连接字符:

原型:strncat(char target[], const char source[], int numchars);

功能:将字符串source的前numchars个字符接到字符串target的后面

例程:

#include

#include

void main(void)

{

  char str1[] = { "Tsinghua "};

  char str2[] = { "Computer"};

  cout <

}

运行结果:Tsinghua Com

5.字符串比较:

原型:int strcmp(const char firststring[], const char secondstring);

功能:比较两个字符串firststringsecondstring

例程:

#include

#include

void main(void)

{

  char buf1[] = "aaa";

  char buf2[] = "bbb";

  char buf3[] = "ccc";

  int ptr;

  ptr = strcmp(buf2,buf1);

  if(ptr > 0)

   cout <<"Buffer 2 is greater than buffer 1"<

  else

   cout <<"Buffer 2 is less than buffer 1"<

  ptr = strcmp(buf2,buf3);

  if(ptr > 0)

   cout <<"Buffer 2 is greater than buffer 3"<

  else

   cout <<"Buffer 2 is less than buffer 3"<

}

运行结果是:Buffer 2 is less than buffer 1

                  Buffer 2 is greater than buffer 3

6.字符统计:

原型:strlen( const char string[] );

功能:统计字符串string中字符的个数

例程:

#include

#include

void main(void)

{

  char str[100];

  cout <<"请输入一个字符串:";

  cin >>str;

  cout <<"The length of the string is :"<"<

}

运行结果The length of the string is x (x为你输入的字符总数字)

注意:strlen函数的功能是计算字符串的实际长度,不包括'\0'在内。另外,strlen函数也可以直接测试字符串常量的长度,如:strlen("Welcome")

 

阅读(1168) | 评论(0) | 转发(1) |
0

上一篇:extern用法详解

下一篇:linux磁盘配额管理

给主人留下些什么吧!~~