C++ 中最后一个单词的长度
假设我们有一个字符串 s。s 可以包含任何英文字母和空格。我们必须找出字符串中最后一个单词的长度。如果没有最后一个单词,则返回 0。
因此,如果输入像 "I love Programming" 这样,则输出将是 11
为了解决这个问题,我们将按照以下步骤进行操作:
n := 0
对于字符串中的每个单词 temp:
n := temp 的大小
返回 n
示例
让我们看看以下实现来更好地理解:
#include <bits/stdc++.h> using namespace std; class Solution { public: int lengthOfLastWord(string s){ stringstream str(s); string temp; int n = 0; while (str >> temp) n = temp.size(); return n; } }; main(){ Solution ob; cout << (ob.lengthOfLastWord("I love Programming")); }
输入
"I love Programming"
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
11
广告