Skip to content

字符串

概念

字符串实际上就是一位字符数组以/0结尾

定义一个字符串

  1. char str[] = {'Y','E','S','\0'};
  2. char str[]= "YES";

输出

c
#include <stdio.h>
 
int main ()
{
   char str[6] = {'Y', 'E', 'S', '\0'};
 
   printf("message: %s\n", str );
 
   return 0;
}

字符串函数

string.h 中有很多操作字符串的函数

c
#include <stdio.h>
#include <string.h>

int main ()
{
    char str1[20] = "Hello";
    char str2[20] = "World";
    
    
    /* 复制 str2 到 str1 */
    strcpy(str1,str2);
    printf("strcpy( str1, str2) :  %s\n", str1);
    
    /* 连接 str1 和 str2 */
    strcat(str1,str2);
    printf("strcat( str1, str2):   %s\n", str1 );
    
    /* 连接后,str1 的总长度 */
    printf("strlen(str1) :  %d\n", strlen(str1) );
    
    /* 比较两个字符串 */
    printf("mapper ? %d\n",strcmp(str1,"world"));
    printf("mapper ? %d\n",strcmp(str1,"World"));
    printf("mapper ? %d\n",strcmp(str1,"WorldWorld"));
    
    /* 查找字符并返回指针 */
    char a = 'o';
    int *o = strchr(str1,a);
    printf("find first by = %p\n",o);
    
    /* 查找字符串并返回指针 */
    char b[]="ld";
    int *ld = strstr(str1,b);
    printf("find first by = %p\n",ld);
    
    return 0;
}