纯C的字符串问题

string.h

char* 复制到char *

strdup

函数名:strdup
功 能: 将串拷贝到新建的位置处
用 法: char *strdup(char *str);
程序例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>
 
#include<string.h>
 
#include<alloc.h>
 
int main(void)
 
{
 
char*dup_str,*string="abcde";
 
dup_str=strdup(string);
 
printf("%s ",dup_str);
 
free(dup_str);
 
return 0;
 
}
 
 

strncmp

函数名:strncmp
功 能: 串比较
用 法: intstrncmp(char *str1, char *str2, int maxlen);
程序例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<string.h>
#include<stdio.h>
int main(void)
{
char *buf1="aaabbb",*buf2="bbbccc",*buf3="ccc";
int ptr;
 
ptr=strncmp(buf2,buf1,3);
 
if(ptr>0)
printf("buffer2 is greater than buffer1 ");
else
printf("buffer2 is less than buffer1 ");
 
ptr=strncmp(buf2,buf3,3);
 
if(ptr>0)
printf("buffer2isgreaterthanbuffer3 ");
else
printf("buffer2islessthanbuffer3 ");
return0;
}

strncpy

函数名:strncpy
功 能: 串拷贝
用 法: char *strncpy(char *destin, char *source, int maxlen);
程序例:
1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>
#include<string.h>
int main(void)
{
char string[10];
char*str1="abcdefghi";
strncpy(string,str1,3);
string[3]='';
printf("%s ",string);
return 0;
}
 
 

strtok

函数名:strtok
功 能: 查找由在第二个串中指定的分界符分隔开的单词
用 法: char *strtok(char *str1, char *str2);
程序例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<string.h>
#include<stdio.h>
intmain(void)
{
charinput[16]="abc,d";
char*p;
 
/*strtokplacesaNULLterminator
infrontofthetoken,iffound*/
 
p=strtok(input,",");
if(p)printf("%s ",p);
 
/*AsecondcalltostrtokusingaNULL
asthefirstparameterreturnsapointer
tothecharacterfollowingthetoken*/
 
p=strtok(NULL,",");
if(p)printf("%s ",p);
return0;
}
 
 

strupr

函数名:strupr
功 能: 将串中的小写字母转换为大写字母
用 法: char *strupr(char *str);
程序例:
1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h>
#include<string.h>
intmain(void)
{
charstring[]="abcdefghijklmnopqrstuvwxyz",*ptr;//定义为数组才能修改
 
/*convertsstringtouppercasecharacters*/
 
ptr=strupr(string);
printf("%s ",ptr);
return0;
}
 
 

strlen

函数名:strlen
功能: strlen函数求的是字符串的长度,它求得方法是从字符串的首地址开始到遇到第一个''停止计数,如果你只定义没有给它赋初值,这个结果是不定的,它会从字符串首地址一直记下去,直到遇到''才会停止。
原型:size_tstrlen(const char *s);
1
2
3
4
5
6
7
8
9
10
#include<stdio.h>
#include<string.h>
int main()
{
int i=0;
char*he="Hello,world";
i=strlen(he);
printf("字符串长度为%d ",i);
return 0;
}
运行结果:
字符串长度为11
 

strcpy

函数名:strcpy
功 能: 拷贝一个字符串到另一个
用 法: char *strcpy(char *destin, char *source);
程序例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<stdio.h>
 
#include<string.h>
 
int main(void)
 
{
 
char string[10];
 
char*str1="abcdefghi";
 
strcpy(string,str1);
 
printf("%s ",string);
 
return 0;
 
}

strncpy

函数名:strncpy
原型:char *strncpy(char *dest, char *src,size_tn);
功能:将字符串src中最多n个字符复制到字符数组dest中(它并不像strcpy一样遇到NULL才停止复制,而是等凑够n个字符才开始复制),返回指向dest的指针

strcat

用strcat的结果显示用strcat的结果显示
函数名:strcat
功 能: 字符串拼接函数
用 法: char *strcat(char *destin, char *source);
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/orangezs/p/8533840.html