strcpy sprintf strcat的用法

1.strcpy

	char arr1[] = "abcdefghj";
    char arr2[] = "3233"; 
    printf("%s\n", arr1);//3233从arr1起始位置开始
    printf("%s\n", arr2);//3233
	
	strcpy(arr1 + 2, arr2);
    printf("%s\n", arr1);//ab3233 
    printf("%s\n", arr2);//3233

2.strcat

    char arr3[] = "11131334";
    char arr4[] = "jiayou";
    strcat(arr3, arr4);
    printf("%s\n", arr3);//11131334jiayou  若arr3中存在\0则从\0前面开始拼接
    printf("%s\n", arr4);//jiayou
  1. sprintf
    //整数
   int num = 1234;
   char str[20];
   sprintf(str, "%d", num);
   printf("%s\n", str); // 输出:1234

   //字符串
   char name[20] = "Allen";
   char str[50];
   sprintf(str, "My name is %s.", name);
   printf("%s\n", str); // 输出:My name is Allen.

  //浮点
  float num = 3.14;
  char str[20];
  sprintf(str, "%.2f", num);
  printf("%s\n", str); // 输出:3.14
  
  //格式化输出
  char str[50];
  int a = 10, b = 20, c = 30;
  sprintf(str, "a = %d, b = %d, c = %d, a + b + c = %d", a, b, c, a + b + c);
  printf("%s\n", str); // 输出:a = 10, b = 20, c = 30, a + b + c = 60
 
 //特殊字符转义输出
 char str[50];
 sprintf(str, "This is a double quote \" and this is a backslash \\.");
 printf("%s\n", str); // 输出:This is a double quote " and this is a backslash \.
//在需要输出引号、反斜杠等特殊字符时,可以使用反斜杠对其进行转义

//组合字符串
char str[100];
char *str1 = "Hello";
char *str2 = "World";
sprintf(str, "%s %s!", str1, str2);
printf("%s\n", str); // 输出:Hello World!
//可以通过将多个字符串拼接起来,输出一个新的字符串

你可能感兴趣的:(c)