C语言—strcpy()

作者:追风剑情 发布于:2019-10-30 19:56 分类:C

strcpy()函数用来拷贝字符串。

示例

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <stdbool.h>
  6. //引入字符串函数string.h
  7. //一些ANSI之前的系统使用strings.h头文件,而
  8. //有些系统可能根本没有字符串头文件。
  9. #include <string.h>
  10.  
  11. #define SIZE 40
  12. #define LIM 5
  13.  
  14. char * s_gets(char * st, int n);
  15.  
  16. //argc: 参数个数 argv[]: 参数数组
  17. int main(int argc, char *argv[])
  18. {
  19. char qwords[LIM][SIZE];
  20. char temp[SIZE];
  21. int i = 0;
  22.  
  23. printf("Enter %d words beginning with q:\n", LIM);
  24. while (i < LIM && s_gets(temp, SIZE))
  25. {
  26. //if (strncmp(temp, "q", 1) != 0)
  27. if (temp[0] != 'q')
  28. printf("%s doesn't begin with q!\n", temp);
  29. else
  30. {
  31. strcpy(qwords[i], temp);
  32. i++;
  33. }
  34. }
  35. puts("Here are the words accepted:");
  36. for (i = 0; i < LIM; i++)
  37. puts(qwords[i]);
  38.  
  39. //char target[20];
  40. //int x;
  41. //x = 50; //数字赋值
  42. //strcpy(target, "Hi ho!"); //字符串赋值
  43. //target = "So long"; //语法错误
  44. //char * str;
  45. //有问题,str未初始化,该字符串可能被拷贝到任意地方
  46. //strcpy(str, "The C of Tranquility");
  47.  
  48. system("pause");
  49. return 0;
  50. }
  51.  
  52. char * s_gets(char * st, int n)
  53. {
  54. char * ret_val;
  55. int i = 0;
  56. ret_val = fgets(st, n, stdin);
  57. if (ret_val) //即,ret_val != NULL
  58. {
  59. while (st[i] != '\n' && st[i] != '\0')
  60. i++;
  61. if (st[i] == '\n')
  62. st[i] = '\0';
  63. else
  64. while (getchar() != '\n')
  65. continue;
  66. }
  67. return ret_val;
  68. }

运行测试
111.png

示例:strcpy()的返回值

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <stdbool.h>
  6. //引入字符串函数string.h
  7. //一些ANSI之前的系统使用strings.h头文件,而
  8. //有些系统可能根本没有字符串头文件。
  9. #include <string.h>
  10.  
  11. #define SIZE 40
  12. #define WORDS "beast"
  13.  
  14. //argc: 参数个数 argv[]: 参数数组
  15. int main(int argc, char *argv[])
  16. {
  17. const char * orig = WORDS;
  18. char copy[SIZE] = "Be the best that you can be.";
  19. char * ps;
  20. puts(orig);
  21. puts(copy);
  22. //将orig拷贝到copy的第7个位置并覆盖之后的字符
  23. //ps指向copy的7个索引
  24. ps = strcpy(copy + 7, orig);
  25. puts(copy);
  26. puts(ps);
  27.  
  28. system("pause");
  29. return 0;
  30. }

运行测试
1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号