计算 字符串的长度
/*
?* 計算字符串長度。
?* 中間涉及了指針的使用。
?* 方式1:分配了內存
?* 方式2:分配了靜態的數據。
?2??*?計算字符串長度。
?3??*?中間涉及了指針的使用。
?4??*?方式1:分配了內存
?5??*?方式2:分配了靜態的數據。
?6??*/
?7?#include<stdio.h>
?8?#include<stdlib.h>
?9?
10?//計算長度的函數
11?int?length(char?*p)
12?{
13?????int?n;
14?????n=0;
15?????while(*p!='\0')
16?????{
17?????????n++;
18?????????p++;
19?????}
20?????
21?????return?n;
22?}
23?
24?int?main()
25?{
26?????int?len;
27?????
28?????//沒有這樣必要分配。
29?????char?*str[20];
30?
31?????//?方式1:?可以分配一個內存進行操作
32?????str[0]=(char*)malloc(sizeof(char)*30);????
33?????scanf("%s",str[0]);
34?
35?????//方式2:?用賦值的方式也相當于分配了內在。
36?????//str[1]="zhengmian?String,?Hello?anybody?not?dead!";
37?????len=length(str[0]);
38?
39?????//方式1的內存釋放。
40?????free(str[0]);
41?????printf("%d\n",len);
42?????return?0;
43?}
?* 計算字符串長度。
?* 中間涉及了指針的使用。
?* 方式1:分配了內存
?* 方式2:分配了靜態的數據。
?*/
?
?1?/*?2??*?計算字符串長度。
?3??*?中間涉及了指針的使用。
?4??*?方式1:分配了內存
?5??*?方式2:分配了靜態的數據。
?6??*/
?7?#include<stdio.h>
?8?#include<stdlib.h>
?9?
10?//計算長度的函數
11?int?length(char?*p)
12?{
13?????int?n;
14?????n=0;
15?????while(*p!='\0')
16?????{
17?????????n++;
18?????????p++;
19?????}
20?????
21?????return?n;
22?}
23?
24?int?main()
25?{
26?????int?len;
27?????
28?????//沒有這樣必要分配。
29?????char?*str[20];
30?
31?????//?方式1:?可以分配一個內存進行操作
32?????str[0]=(char*)malloc(sizeof(char)*30);????
33?????scanf("%s",str[0]);
34?
35?????//方式2:?用賦值的方式也相當于分配了內在。
36?????//str[1]="zhengmian?String,?Hello?anybody?not?dead!";
37?????len=length(str[0]);
38?
39?????//方式1的內存釋放。
40?????free(str[0]);
41?????printf("%d\n",len);
42?????return?0;
43?}
轉載于:https://www.cnblogs.com/zhengmian/archive/2012/04/28/string_length.html
總結
- 上一篇: 一个简单的GridView分页
- 下一篇: Java心得--键值、枚举器