sprintf、atoi、strlen、strcat、memset、sizeof的一些用法总结

转载---点击打开链接

一、sprintf的用法

// 需要#include <stdio.h>

// 将字符串打印到arr数组    

sprintf(arr, "%s", "abc"); 


// 将整数转换为字符串存入arr数组

sprintf(arr, "%d", 123);//将整数123转换成字符串"123" 

sprintf(arr, "%02d", 1); //将整数1转换成字符串"01" 


二、atoi的用法

// 将字符串转换为整数,需要#include<stdlib.h>

a = atoi("1243"); //a=1243

a = atoi("-1243"); //a=-1243(负整数)

a = atoi("+1243"); //a=1243(正整数,无正号)

a = atoi("01"); //a=1

a = atoi("+0012"); //a=12(正整数,无正号)

a = atoi("-0012"); //a=-12(整数)


三、strlen的用法

1、strlen 字符串的结果就是字符串的字符个数,不含终止符。

2、strlen 数组名

(1)如果数组没有被初始化,那么结果是无效值

(2)如果数组被字符串初始化,那么结果是字符串字符个数,不含终止符


四、strcat的用法

strcat(dst, src);

将src指向的字符串拼接到dst数组里,

且是从dst数组的第一个字符串终止符开始覆盖,

故,如果dst数组为空那么需要使用

0("\0")初始化数组dst.


五、memset的用法

// 需要#include <string.h>

memset(dst, ch, n); // dst中前n个字节 用 ch替换并返回 dst 

memset(arr, 0, sizeof(arr)); //将数组全部清零


六、sizeof的用法

 1、在标准C里面,sizeof是不能用于函数类型;
sizeof cannot be used with function types, incomplete types, or bit-field glvalues.
When applied to a reference type, the result is the size of the referenced type.

2、在GNU C里面,sizeof 的功能进行的扩展,可以支持函数类型和void;
sizeof is also allowed on void and on function types, and returns 1.
故如果使用GCC编译器,那么sizeof 函数名或者void 的结果为1

3、sizeof 字符串时,要算上字符串的终止符,如sizeof("aa")值为3,

4、sizeof 数组名时,值为数组所占字节数而不是数组元素个数。

猜你喜欢

转载自blog.csdn.net/qq_38405680/article/details/81000668