//解题思路:创建一个指针变量开始指向首元素,通过循环一直移向字符串末尾'\0'停下, //再用尾指针减头指针就等于中间元素的个数,即字符串长度。 #include <iostream> using namespace std; int main() { char str[100] = { 0 }; cin.getline(str, sizeof(str)); // write your code here...... scanf("%s",&str); //获取字符串长度 char* end = str; while(*end != '\0') end++; //找到字符串末尾 printf("%d\n",end - str); //尾指针减头指针等于中间元素的个数 return 0; }
#include <cassert> #include <cstdio> #include <iostream> #include <string> using namespace std; int getline(char* str){ assert(str); int count=0; while (*str!='\0') { count++; str++; } return count; } int main() { char str[100] = { 0 }; //因为scanf取一行字符时碰到空格,制表符,\r,\n就结束了。 //所以用%[^\n],这个格式符的意思是读\n之外的所有字符,也就是说读到/n为止! scanf("%[^\n]",str); int length=getline(str); printf("%d",length); return 0; }
#include <iostream> using namespace std; int main() { char str[100] = { 0 }; cin.getline(str, sizeof(str)); // write your code here...... int i = 0; for (; *(str + i) !='\0' ; i++) { } printf("%d",i); return 0; }