在C语言中,`string.h`头文件包含了一系列处理字符串的函数。以下是一些常用的`string.h`函数及其用法:
1. **strlen() - 计算字符串长度**
  ```c
  #include <string.h>
  size_t strlen(const char *str);
  ```
  示例:
  ```c
  const char *myString = "Hello, World!";
  size_t length = strlen(myString);
  printf("String length: %zu\n", length);
  ```
2. **strcpy() - 复制字符串**
  ```c
  #include <string.h>
  char *strcpy(char *dest, const char *src);
  ```
  示例:
  ```c
  char destination[20];
  const char *source = "Copy me!";
  strcpy(destination, source);
  printf("Copied string: %s\n", destination);c++strcpy函数用法
  ```
3. **strcat() - 拼接字符串**
  ```c
  #include <string.h>
  char *strcat(char *dest, const char *src);
  ```
  示例:
  ```c
  char str1[20] = "Hello, ";
  const char *str2 = "World!";
  strcat(str1, str2);
  printf("Concatenated string: %s\n", str1);
  ```
4. **strcmp() - 比较字符串**
  ```c
  #include <string.h>
  int strcmp(const char *str1, const char *str2);
  ```
  示例:
  ```c
  const char *s1 = "apple";
  const char *s2 = "orange";
  int result = strcmp(s1, s2);
  if (result == 0) {
      printf("Strings are equal.\n");
  } else if (result < 0) {
      printf("s1 is less than s2.\n");
  } else {
      printf("s1 is greater than s2.\n");
  }
  ```
5. **strncmp() - 指定长度比较字符串**
  ```c
  #include <string.h>
  int strncmp(const char *str1, const char *str2, size_t n);
  ```
  示例:
  ```c
  const char *s1 = "apple";
  const char *s2 = "apples";
  int result = strncmp(s1, s2, 5);  // 比较前五个字符
  ```
6. **strchr() - 在字符串中查字符**
  ```c
  #include <string.h>
  char *strchr(const char *str, int c);
  ```
  示例:
  ```c
  const char *myString = "Hello, World!";
  char *result = strchr(myString, 'W');

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。