C++字符串使用整理

strcpy

(一)函数定义原型:

char *strcpy(char *dest,const char *src);

头文件:string.h 或 cstring

格式:strcpy

功能:将字符数组2中的字符串复制到字符数组1中。

说明:

(1)字符数组1的长度必须大于等于字符数组2的长度。

(2)复制时连同字符串后面的'\0'一起复制到字符数组1中。

(3)不能用赋值语句将一个字符串常量或字符数组直接赋给一个字符数组。

(二)使用样例

#include <iostream> 
#include <string.h>
using namespace std; 
int main( ) 
{ 
char string[10]; 
char *str1 = "abcdefghi"; 
stpcpy(string, str1); 
cout<<string; 
return 0; 
} 

strcat

(一)函数定义原型

char *stpcpy(char *destin, char *source);

头文件:string.h 或 cstring

格式:strcat

功能:字符串拼接

(二)使用样例

#include <string.h> 
#include <iostream> 
using namespace std;
int main( ) 
{ 
char destination[25]; 
char *blank = " ", *c = "C++", *Borland = "Borland"; 
strcpy(destination, Borland); 
strcat(destination, blank); 
strcat(destination, c); 
cout<<destination; 
return 0; 
} 

strcmp

(一)函数定义原型

int strcmp(char *str1, char *str2); 

头文件:string.h 或 cstring

格式:strcmp

功能:串比较

(二)使用样例

#include <string.h> 
#include <iostream> 
using namespace std;
int main( ) 
{ 
char *buf1 = "aaa", *buf2 = "bbb", *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; 
return 0; 
} 

strlwr

(一)函数定义原型

extern char *strlwr(char *s);

头文件:string.h 或 cstring

格式:strlwr

功能:将字符串s转换为小写形式

说明:只转换s中出现的大写字母,不改变其它字符。返回指向s的指针。

(二)使用样例

#include<iostream>
#include<string.h>
using namespace std;
int main()
 {
   char a[]="ASDFasdf54afASDF";  
   cout<<strlwr(a)<<endl;
    return 0;
 }

strupr

(一)函数定义原型

char *strupr(char *str); 

头文件:string.h 或 cstring

格式:strupr

功能:将串中的小写字母转换为大写字母

(二)使用样例

#include<iostream>
#include<string.h>
using namespace std;
int main( ) 
{ 
char *string = "abcdefghijklmnopqrstuvwxyz", *ptr; 
ptr = strupr(string); 
cout<<ptr; 
return 0; 
} 

strncpy

(一)函数定义原型

char *strncpy(char *destin, char *source, int maxlen); 

头文件:string.h 或 cstring

格式:strncpy

功能:串拷贝

(二)使用样例

#include<iostream>
#include<string.h>
using namespace std;
int main( ) 
{ 
char string[10]; 
char *str1 = "abcdefghi"; 
strncpy(string, str1, 3); 
string[3] = '/0'; 
cout<<string; 
return 0; 
} 

strncmp

(一)函数定义原型

int strncmp(char *str1, char *str2, int maxlen);

头文件:string.h 或 cstring

格式:strncmp

功能:串比较

(二)使用样例

#include<iostream>
#include<string.h>
using namespace std;
int main( ) 
{ 
char *buf1 = "aaabbb", *buf2 = "bbbccc", *buf3 = "ccc"; 
int ptr; 
ptr = strncmp(buf2,buf1,3); 
if (ptr > 0) 
cout<<"buffer 2 is greater than buffer 1"<<endl; 
else 
cout<<"buffer 2 is less than buffer 1"<<endl; 
ptr = strncmp(buf2,buf3,3); 
if (ptr > 0) 
cout<<"buffer 2 is greater than buffer 3"<<endl; 
else 
cout<<"buffer 2 is less than buffer 3"<<endl; 
return 0; 
} 
posted @ 2019-04-11 23:36  黄溶佳  阅读(589)  评论(0编辑  收藏  举报