到目前为止,一维数组最常用的地方还是字符串.C++支持两种类型的字符串.第一种是以空字符结束的字符串,它是一个一维字符数组,以空字符做为结束.(空字符就是0)这是C语言中定义的唯一一种字符串类型,而且被广泛的应用.有时,空字符结尾字符串也被称为C-strings.C++还定义了一个字符串类,名叫string,它提供了一种处理字符串的面向对象的方式.string类将在后面讲述,现在我们来讲解空字符结尾的字符串.
当声明一个数组用来保存空字符结尾的字符串的时候,我们需要把数组的长度声明为比字符串的最大可能长度大1个字符.例如,需要声明一个字符数组str用来保存一个10个字符长的字符串.我们需要这样写:
char str[11];
这样就可以为字符串结尾的空字符预留一个字符的空间.
当你需要在程序中使用一种用引号括起来的字符串常量,编译器也自动创建了空字符结尾的字符串.字符串常量是用双引号括起的一列字符.例如:
"hello here"
不需要手工在字符串的结尾加上null字符,编译器会自动处理.
C/C++提供了大量的用来处理空字符结尾的字符串的函数,最常用的有:
NAME Funtion
strcpy( s1, s2 ) Copies s2 into s1.
strcat( s1, s2 ) Concatenate s2 onto the end of s1.
strlen( s1 ) Return the length of s1.
strcmp( s1 ) Returns 0 if s1 and s2 are the same;less than 0 if s1<s2;greater than 0 if s1>s2.
strchr( s1, ch ) Returns a pointer to the first occurence of ch in s1.
strstr( s1, s2 ) Returns a pointer to the first occurence of s2 in s1.
这些函数都要使用标准头文件string.h.(C++需要使用C风格字符串<cstring>).下面的例子演示了这些函数的用法:
#include <stdio.h>
#include <string.h>
int main( void )
{
char s1[80], s2[80];
gets( s1 );
gets( s2 );
printf( "lengths: %d %d/n", strlen(s1), strlen(s2) );
if( !strcmp(s1,s2) ) printf( "The strings are equal/n" );
strcat( s1, s2 );
printf( "%s", s1 );
strcpy( s1, "This is a test./n" );
printf( "%s", s1 );
if( strchr("hello",'e') ) printf( "e is in hello/n" );
if( strstr("hi there","hi") printf( "found hi " );
return 0;
}
如果运行这些程序,然后输入字符串"hello"和"hello",程序的输出将是:
lengths: 5 5
The string are equal
hellohello
This is a test.
e is in hello
found hi
记住,当字符串相等的时候,strcmp()函数返回的是false也就是0.如果你需要检测是否相等,那么确保用!操作符将条件表达式取反,就像这个例子中一样.
尽管C++中定义了字符串类,现有的程序中空字符结尾的字符串仍然应用的很广泛.因为它能够有更高的效率,而且能允许程序员进行更细节的操控.不过,对于一些简单的字符串处理事务,C++的string类提供了更方便的方式.