连接字符串-sprintf

来源:互联网 发布:淘宝号可以改账户名吗 编辑:程序博客网 时间:2024/05/16 13:47
    在写程序中,有时需要用到连接2个字符串,在这里介绍一下2个函数。
函数一:sprintf

参考:http://oss.lzu.edu.cn/blog/article.php?tid_877.html

定义如下:
int sprintf( char *buffer, const char *format [, argument] ... );

说明如下:
sprintf是个变参函数,除了前两个参数类型固定外,后面可以接任意多个参数。
而它的精华,显然就在第二个参数:格式化字符串上。

返回值:较少有人注意printf/sprintf函数的返回值,但有时它却是有用的,spritnf返回了本次函数调用最终打印到字符缓冲区中的字符数目。
也就是说每当一次sprinf调用结束以后,你无须再调用一次strlen便已经知道了结果字符串的长度


用法如下:

  1.把整数打印到字符串中:
   sprintf最常见的应用之一莫过于把整数打印到字符串中,所以,spritnf在大多数场合可以替代itoa。
如:
//把整数123打印成一个字符串保存在s中。

sprintf(s, "%d", 123);   //产生"123" 

  2.连接字符串
 sprintf的格式控制串中既然可以插入各种东西,并最终把它们“连成一串”,自然也就能够连接字符串,
从而在许多场合可以替代strcat,但sprintf能够一次连接多个字符串(自然也可以同时在它们中间插入别的内容,总之非常灵活)。
比如:

char* who = "I";

char* whom = "CSDN";

sprintf(s, "%s love %s.", who, whom); //产生:"I love CSDN. "     

   以下是2个sprintf例子:
例一:
main()
{
    int i=0;
    char *b="link";
//  char s[10];
    char *s;
    s=(char *)malloc(10);
    for(i=0;i<5;i++){
    sprintf(s,"%s%d",b,i);

        printf("%s/n",s);
    }
}

输出结果:
link0
link1
link2
link3
link4

例二:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
    srand(time(0));
    char s[64];
    int offset = 0;
    int i=0;
    for( i = 0; i < 10; i++) {
           offset += sprintf(s + offset, "%d,", rand() % 100);  //sprintf函数返回值为该数组长度,相当于strlen的值
       }   
    s[offset - 1] = '/n';//将最后一个逗号换成换行符。
    printf("The result is:%s/n",s);
    return 0;
}   

输出结果:
The result is:66,26,38,66,31,96,65,81,63,77


函数二:

函数名: strcat
功 能: 字符串拼接函数
用 法: char *strcat(char *destin, char *source);
程序例: 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{char str1[30]="abcde",str2[10]="123";
    strcat(str1,str2);
    printf("The merge result is:%s/n",str1);
}

输出结果:
The merge result is:abcde123

二者区别:
   sprintf的格式控制串中既然可以插入各种东西,并最终把它们“连成一串”,自然也就能够连接字符串,
从而在许多场合可以替代strcat,但sprintf能够一次连接多个字符串(自然也可以同时在它们中间插入别的内容,总之非常灵活)
原创粉丝点击