C中常用字符串处理函数

来源:互联网 发布:无线淘宝logo尺寸 编辑:程序博客网 时间:2024/05/21 10:19

1)字符串输出函数

   puts(字符数组名);

功能:把字符数组中的字符串输出到显示器。

例子:

#include <stdio.h>

void main()
{
char c[]="hello world\n";
puts(c);
}


2)字符串输入函数

   gets(字符数组名)

功能:从标准输入设备上输入一个字符串

例子:

#include <stdio.h>


int main()
{
char st[15];
printf("input string:");
gets(st);
puts(st);


return 0;
}


3)字符串连接函数

    strcat(字符数组名1, 字符数组名2);

功能:把字符数组2中的字符串连接到 字符数组1中字符串的后面,并删除字符串1后的结束标志‘\0’,函数的返回值是字符数组1的首地址。

例子:

#include <stdio.h>
#include <string.h>


int main()
{
static char st1[30]="My name is:";
char st2[10];
printf("input your name:");
gets(st2);
strcat(st1, st2);
puts(st1);


return 0;
}


4) 字符串拷贝函数

     strcpy(字符数组名1, 字符数组名2);

功能:把字符数组2中的字符串复制到 字符数组1中,字符串1后的结束标志‘\0’也一同复制,字符数组2也可以是一个字符串常量,这时相当于把一个字符串赋给一个字符数组,

例子:

#include <stdio.h>
#include <string.h>
int main()
{
char st1[15], st2[]="C language";
strcpy(st1, st2);
puts(st1);

return 0;
}


5) 字符串比较函数

    strcmp(字符数组名1, 字符数组名2)

功能:按ASCII码值的大小逐个比较两个字符串数组中的各个字符,直到出现不同的字符或遇到'\0'为止,函数的返回值有三种情况:

1)字符串1=字符串2 返回值为0;

2) 字符串1 > 字符串2,返回值为以正整数

3) 字符串1< 字符串2,返回值为一负整数。

例子:

#include <stdio.h>
#include <string.h>
int main()
{
int k;
static char st1[15], st2[] = "abc";
printf("input a string:");
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");


return 0;
}


6) 求字符串长度函数   

     strlen(字符数组名)

功能:求字符串的实际长度(不含字符串结束标志'\0'),并作为函数返回值,

例子:

#include <stdio.h>
#include <string.h>


int main()
{
int k;
static char str[]="abcde";
k=strlen(str);
printf("The length of the string is %d\n", k);


return 0;
}

原创粉丝点击