#include <iostream.h>
#include <string.h>
void main(void)
{
char str1[10] = {"Tsinghua "};
char str2[10] = {"Computer"};
cout<<strncpy(str1,str2,3)<<endl;
}
運行結果:Comnghua
注意:字串source中前numchars個字元將覆蓋掉字串destination中前numchars個字元!
strcat(char target[], const char source[]);
strcat:將字串source接到字串target的後面。
strcat函數應用舉例
原型:strcat(char target[], const char source[]);
功能:將字串source接到字串target的後面
常式:
#include <iostream.h>
#include <string.h>
void main(void)
{
char str1[] = {"Tsinghua "};
char str2[] = {"Computer"};
cout<<strcpy(str1,str2)<<endl;
}
運行結果:Tsinghua Computer
注意:在定義字元數組1的長度時應該考慮字元數組2的長度,因為串連後新字串的長度為兩個字串長度之和。進行字串串連後,字串1的結尾符將自動被去掉,在結尾串末尾保留新字串後面一個結尾符。
strncat(char target[], const char source[], int numchars);
strncat:將字串source的前numchars個字元接到字串target的後面。
strncat函數應用舉例:
原型:strncat(char target[], const char source[], int numchars);
功能:將字串source的前numchars個字元接到字串target的後面
常式:
#include <iostream.h>
#include <string.h>
void main(void)
{
char str1[] = {"Tsinghua "};
char str2[] = {"Computer"};
cout<<strncat(str1,str2,3)<<endl;
}
運行結果:Tsinghua Com
int strcmp(const char firststring[], const char secondstring);
strcmp:比較兩個字串firststring和secondstring。
strcmp函數應用舉例
原型:int strcmp(const char firststring[], const char secondstring);
功能:比較兩個字串firststring和secondstring
常式:
#include <iostream.h>
#include <string.h>
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"<<endl;
else
cout<<"Buffer 2 is less than buffer 1"<<endl;
ptr = strcmp(buf2,buf3);
if(ptr > 0)
cout<<"Buffer 2 is greater than buffer 3"<<endl;
else
cout<<"Buffer 2 is less than buffer 3"<<endl;
}
運行結果是:Buffer 2 is less than buffer 1
Buffer 2 is greater than buffer 3
strlen( const char string[] );
strlen:統計字串string中字元的個數。
strlen函數應用舉例
原型:strlen( const char string[] );
功能:統計字串string中字元的個數
常式:
#include <iostream.h>
#include <string.h>
void main(void)
{
char str[100];
cout<<"請輸入一個字串:";
cin>>str;
cout<<"The length of the string is :"<<strlen(str)<<"個"<<endl;
}
運行結果The length of the string is x (x為你輸入的字元總數字)
注意:strlen函數的功能是計算字串的實際長度,不包括'/0'在內。另外,strlen函數也可以直接測試字串常量的長度,如:strlen("Welcome")。