标签:style blog ar io color sp for on div
1. 字符数组
1 #include <stdio.h> 2 3 void concat(char result[], const char str1[], int n1, 4 const char str2[], int n2) 5 { 6 int i, j; 7 // put str1 and str2 in result in sequence 8 for (i=0; i<n1; i++) 9 result[i] = str1[i]; 10 for (j=0; j<n1; j++) 11 result[i+j] = str2[j]; 12 } 13 14 int main(void) 15 { 16 17 void concat(char result[], const char str1[], int n1, 18 const char str2[], int n2); 19 char str1[6] = {‘H‘,‘e‘,‘l‘,‘l‘,‘o‘,‘,‘}; 20 char str2[6] = {‘w‘,‘o‘,‘r‘,‘l‘,‘d‘,‘!‘}; 21 char result[12]; 22 concat(result, str1, 6, str2, 6); 23 int i;
这种情形下每次都要声明字符串长度不免有些麻烦,借助空字符‘\0‘( aka, null ),来实现自动判断字符串长度。
1 #include <stdio.h> 2 3 int len(char string[]) 4 { 5 // get the length of a string which ends with a ‘\0‘ 6 int length=0; 7 while (string[length] != ‘\0‘) 8 length++; 9 return length; 10 } 11 12 13 int main(void) 14 { 15 16 int len(char string[]); 17 char name[] = {‘A‘,‘b‘,‘r‘,‘a‘,‘h‘,‘a‘,‘m‘,‘\0‘}; 18 printf("%i\n", len(name)); 19 return 0; 20 }
实际上,char word[] = {"hi!"}; 等效于 char word[] = {‘h‘, ‘i‘, ‘!‘, ‘\0‘}; ,但是书写上美观简单得多。
标签:style blog ar io color sp for on div
原文地址:http://www.cnblogs.com/omnipotent/p/4171224.html