题解 | 字符串最后一个单词的长度
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&tqId=21224&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D2%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
#include <iostream> using namespace std; int main() { string a; getline(cin,a); int b = a.length(); int c = 0;//判断是否接收到第一个非空字符 int d = 0; while(true){ b = b -1; if(a[b]==' '&&c!=0||b==-1){//边界值限定,if语句不可轻易调换位置 break; } if(a[b]!=' '&&c!=0){ d = d + 1; continue; } if(a[b]==' '&&c==0){ continue; } if(a[b]!=' '&&c==0){ c = 1; d = d + 1; continue; } } cout<<d; }