c语言中string怎么用啊

Python027

c语言中string怎么用啊,第1张

C语言提供了丰富的字符处理函数, 大致可分为字符串的输入、输出、合并、修改、比较、转换、复制、搜索几类。 使用这些函数可大大减轻编程的负担。用于输入输出的字符串函数, 在使用前应包含头文件"stdio.h" ; 使用其它字符串函数则应包含头文件"string.h"。 下面介绍几个最常用的字符串函数。

1.字符串输出函数 puts 格式: puts (字符数组名) 功能:把字符数组中的字符串输出到显示器。 即在屏幕上显示该字符串

#include"stdio.h"

main()

{

static char c[]="BASIC\ndBASE"

puts(c)

}

2.字符串输入函数gets 格式: gets (字符数组名) 功能:从标准输入设备键盘上输入一个字符串。 本函数得到一个函数值,即为该字符数组的首地址。

#include"stdio.h"

main()

{

char st[15]

printf("input string:\n")

gets(st)

puts(st)

}

3.字符串连接函数strcat 格式: strcat (字符数组名1,字符数组名2) 功能:把字符数组2中的字符串连接到字符数组1 中字符串的后面,并删去字符串1后的串标志“\0”。本函数返回值是字符数组1的首地址。

#include"string.h"

main()

{

static char st1[30]="My name is "

int st2[10]

printf("input your name:\n")

gets(st2)

strcat(st1,st2)

puts(st1)

}

4.字符串拷贝函数strcpy 格式: strcpy (字符数组名1,字符数组名2) 功能:把字符数组2中的字符串拷贝到字符数组1中。串结束标志“\0”也一同拷贝。字符数名2, 也可以是一个字符串常量。这时相当于把一个字符串赋予一个字符数组。

#include"string.h"

main()

{

static char st1[15],st2[]="C Language"

strcpy(st1,st2)

puts(st1)printf("\n")

}

5.字符串比较函数strcmp 格式: strcmp(字符数组名1,字符数组名2) 功能:按照ASCII码顺序比较两个数组中的字符串,并由函数返回值返回比较结果。

字符串1=字符串2,返回值=0;

字符串2〉字符串2,返回值〉0;

字符串1〈字符串2,返回值〈0。

本函数也可用于比较两个字符串常量,或比较数组和字符串常量。

#include"string.h"

main()

{ int k

static char st1[15],st2[]="C Language"

printf("input a string:\n")

gets(st1)

k=strcmp(st1,st2)

if(k==0) printf("st1=st2\n")

if(k>0) printf("st1>st2\n")

if(k<0) printf("st1<st2\n")

}

6.测字符串长度函数strlen 格式: strlen(字符数组名) 功能:测字符串的实际长度(不含字符串结束标志‘\0’) 并作为函数返回值。

#include"string.h"

main()

{ int k

static char st[]="C language"

k=strlen(st)

printf("The lenth of the string is %d\n",k)

}

c语言中string的用法为char* strcpy(char* str1,char* str2)一般string函数是用来替代C语言中的字符串的,string 类为我们提供了一个转换函数 c_str(),该函数能够将 string 字符串转换为C风格的字符串,并返回该字符串的 const 指针。