首页 > 其他 > 详细

字串简介

时间:2019-05-15 10:11:52      阅读:98      评论:0      收藏:0      [点我收藏+]

20.字元阵列

  • 字元与字元阵列
  1. 一个字元型别变数可以储放一个字元 char ch = ‘H‘;
  2. 一个字元阵列型别变数可以储放一到多个字元   如:char str [ ] = {‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘,‘\0‘};
  • 字串与字元阵列
  1. 字串是以 ‘\0‘ 表示结尾的字元阵列 
  2. 字元阵列可以用 “字串内容” 进行初始化, 会自动加上 ‘\0‘ 字元 如:char str[] = ‘‘Hello‘‘;
 1 #include <stdio.h>
 2 
 3 void str_print(char str[])
 4 /*
 5  {
 6     int i;
 7     for (i = 0; str[i] != ‘\0‘; i++) {
 8         printf("%c", str[i]);
 9     }
10     printf("\n");
11 } */
12 
13 {
14     printf("%s\n", str);
15 }
16 int main() {
17     char str[] = "Hello world";
18     str_print(str);
19     return 0;
20 }
21 
22 
23 Hello world
24 
25 Process returned 0 (0x0)   execution time : 11.821 s
26 Press any key to continue.

 20.1 计算字串长度的练习

 1 #include <stdio.h>
 2 
 3 int str_len (char str[]) {
 4     int i = 0;
 5     while (str[i] != \0) {
 6         i++;
 7     }
 8     return i;
 9 }
10 
11 
12 int main() {
13     char str[11] = "Hello world"; //C 语言允许字元阵列大小刚好只包含有文字内容的部分,但这样的字元阵列不能直接拿来给一般字串处理函式使用
14     printf("Length: %lu\n", sizeof(str));
15     printf("Length: %d\n", str_len(str));// 字串长度
16     return 0;
17 }
18 
19 Length: 11
20 Length: 12
21 
22 Process returned 0 (0x0)   execution time : 1.246 s
23 Press any key to continue.
 1 #include <stdio.h>
 2 
 3 int str_len (char str[]) {
 4     int i = 0;
 5     while (str[i] != \0) {
 6         i++;
 7     }
 8     return i;
 9 }
10 
11 
12 int main() {
13     char str[12] = "Hello world"; 
14     printf("Length: %lu\n", sizeof(str));
15     printf("Length: %d\n", str_len(str));// 字串长度
16     return 0;
17 }
18 
19 Length: 12
20 Length: 11
21 
22 Process returned 0 (0x0)   execution time : 1.217 s
23 Press any key to continue.

 

字串简介

原文:https://www.cnblogs.com/pxxfxxxx/p/10867528.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!