https://oj.leetcode.com/problems/length-of-last-word/
对一个字符串遍历,求最后一个单词的长度,如果有 ‘ ’,则切开了。
字符串的最后一个字符为 '\0'
NULL和“”是有区别的:NULL是 0x00000 , ""是长度为1的串,里面只有结尾元素,即 “\0”.
class Solution { public: int lengthOfLastWord(const char *s) { int ans = 0; int index = 0; if(s == NULL) return 0; while(s[index] != '\0') { while(s[index] == ' ') index ++; if(s[index] == '\0') break; ans = 0; while(s[index] != ' ' && s[index] != '\0') { ans++; index++; } } return ans; } };