C基础知识(7):字符串

在C语言中,字符串实际上是使用null字符'' 终止的一维字符数组。因此,一个以null结尾的字符串,包含了组成字符串的字符。

C编译器会在初始化数组时,自动把''放在字符串的末尾。所以不需要手动添加。

下面例子是一些常用的字符串函数的用法。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main() {
 5     // (1)复制字符串str1 到字符串str2。(str2改变)
 6     char str1[] = "This is a C program.";
 7     char str2[0];
 8     strcpy(str2, str1);
 9     printf("%s
", str2); // This is a C program.
10 
11     // (2)连接字符串str4 到字符串str3 的末尾。(str3改变)
12     char str3[] = "The program is about ";
13     char str4[] = "string.";
14     strcat(str3, str4);
15     printf("%s
", str3); // The program is about string.
16 
17     // (3)返回字符串的长度。
18     int len = strlen(str1);
19     printf("%d
", len); // 20
20 
21     // (4)如果a,b是相同的,则返回0;如果a<b则返回小于0;如果a>b则返回大于 0
22     char str5[] = "2017-03-01";
23     char str6[] = "2017-05-29";
24     char str7[] = "2016-12-25";
25     char str8[] = "2017-03-01";
26     int res1 = strcmp(str5, str6);
27     int res2 = strcmp(str5, str7);
28     int res3 = strcmp(str5, str8);
29     printf("%d %d %d
", res1, res2, res3); // -2 1 0(<0 >0 =0)
30 
31     // (5)返回一个指针,指向字符串str1中字符h的第一次出现的位置。
32     char *c1 = strchr(str1, 'h');
33     printf("[*c1] = %c
", *c1); // h
34     printf("[c1] = %p
", c1); // 0x7fff5fd0ae01
35     printf("[&str1[1]] = %p
", &str1[1]); // 0x7fff5fd0ae01
36 
37     // (6)返回一个指针,指向字符串str1中字符串is的第一次出现的位置。
38     char *c2 = strstr(str1, "is");
39     printf("[*c2] = %c
", *c2); // i
40     printf("[c2] = %p
", c2); // 0x7fff5fd0ae02
41     printf("[&str1[2]] = %p
", &str1[2]); // 0x7fff5fd0ae02
42 }
原文地址:https://www.cnblogs.com/storml/p/7798597.html