三种方法求字符串长度 | 您所在的位置:网站首页 › java中求字符串长度的函数 › 三种方法求字符串长度 |
在求字符串长度时,第一时间会想到运用strlen这个函数,但对于初学者来说,除了掌握这个函数之外,还应当自己写函数来实现相似的功能。 接下来我列举了三种方法来求字符串长度,供大家参考: (1)运用strlen 注意点:运用该函数时需注意包含string.h头函数 #include #include int main() { char ch[] = "abcdefg"; int len = strlen(ch); printf("字符串长度为%d\n", len); return 0; }(2)自定义my_strlen函数 注意点:拿“abcdefg”字符串举个例子,它在内存中存储的样式为a b c d e f g \0,统计字符串的长度也就是要统计“\0”之前的字符有多少。 那么,设置两个变量,一个用来依次访问字符串中的每一个字符,一个用来统计数量。 #include int my_strlen(char ch[]) { int i = 0; int num = 0; while (ch[i] != '\0') { i++; num++; } return num; } int main() { char ch[] = "abcdefg"; int len = my_strlen(ch); printf("字符串长度为%d\n", len); return 0; }(3)用字符型指针和递归来实现 注意点:求"abcdefg"的字符串长度,可以将其看成1+my_strlen(bcdefg)->1+1+my_strlen(cdefg)->1+1+1+my_strlen(defg)->...一直到指针指向'\0'为止。 #include int my_strlen(char* pr) { if (*pr != '\0') { return my_strlen(pr + 1) + 1; } else { return 0; } } int main() { char ch[] = "abcdefg"; int len = my_strlen(ch); printf("字符串长度为%d\n", len); return 0; } |
CopyRight 2018-2019 实验室设备网 版权所有 |