C语言字符串常用方法


// 字符长度
int strLenght(char *s) {
  int n = 0;
  while (*s != '\0') {
    n++;
    s++;
  }
  return n;
}

// 复制字符串 s2->s1
char *strCopy(char *s1, char *s2) {
  char *p = s1;
  while (*s2 != '\0') {
    *p = *s2;
    s2++;
    p++;
  }
  *p = '\0';
  return s1;
}

// 拼接字符串 s1 = s1+s2
char *strConnect(char *s1, char *s2) {
  char *p = s1;
  while (*p != '\0') {
    p++;
  }
  while (*s2 != '\0') {
    *p = *s2;
    p++;
    s2++;
  }
  *p = '\0';
  return s1;
}

// 比较字符串 s1>s2->1  s1==s2->0 s1<s2->-1 
int strCompare(char *s1, char *s2) {
  int i;
  for (i = 0; s1[i] != '\0' && s2[i] != '\0'; i++) {
    if (s1[i] > s2[i]) {
      return 1;
    } else if (s1[i] < s2[i]) {
      return -1;
    }
  }
  if (s1[i] == '\0' && s2[i] == '\0') {
    return 0;
  } else if (s1[i] != '\0') {
    return 1;
  } else {
    return -1;
  }
}