[c/cpp]:字符计数和文本行计数
一、代码
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 5 6 char input[] = "1\n2\n3\n"; 7 8 9 // string_length = string_real_length + '\0'. 10 // charstring_length = cslen 11 int cslen(char *p){ 12 13 char end='\0'; 14 int size ; 15 16 // init 'size' 17 if(*p==end) { 18 size = 0; 19 } else { 20 size=1; 21 } 22 23 for(char *c=p; *c!=end; c++) { 24 size += 1; 25 } 26 27 //std::cout << "\t[str_len]#\t" << size << std::endl; 28 return size; 29 } 30 31 32 // return numbers of line. line, end with '\n'. 33 // line seperated by '\n' 34 int line_no(char *p) 35 { 36 char *c=p; 37 char line_end = '\n'; 38 char char_end = '\0'; 39 40 int line_num = 0; 41 42 for ( ; *c!=char_end; c++) { 43 //std::cout << "\t[test]#\t" << *c << std::endl; 44 if ( *c==line_end ) { 45 line_num += 1; 46 } 47 } 48 49 50 //std::cout <<"\t[line_no]#\t" << line_num << std::endl; 51 return line_num; 52 } 53 54 55 // test part 56 int main() 57 { 58 std::cout << "\t[string]#\t" << input << std::endl; 59 60 std::cout << "\t[str_len]#\t" << cslen(input) << std::endl; 61 std::cout << "\t[line_no]#\t" << line_no(input) << std::endl; 62 63 return 0 ; 64 }
二、运行结果
[string]# 1 2 3 [str_len]# 7 [line_no]# 3
三、参考资料和工具
1、 cpp在线编辑工具 - https://coliru.stacked-crooked.com/
标签:include,end,char,计数,cpp,文本,size From: https://www.cnblogs.com/lnlidawei/p/18522875