#字符串最后一个单词的长度#_huawei_no.1-2

字符串最后一个单词的长度

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

#include <algorithm>
#include <iostream>
using namespace std;
int main() {
        string s;
        getline(cin, s);
        size_t lastwordlen = 0;
        for (auto i = s.rbegin(); i < s.rend(); i++) {
                if ( *i == ' ') {
                        break;
                   
        }
                lastwordlen++;
           
    }
        cout << lastwordlen << endl;
}
// 64 位输出请用 printf("%lld")

#include <algorithm>
#include <iostream>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    int count = 0;
    reverse(s.begin(), s.end());
    
    // 找到第一个空格的位置
    size_t firstSpacePos = s.find(' ');
    
    // 如果找到了空格,则计算空格之前的字符数量
    if (firstSpacePos != string::npos) {
        count = firstSpacePos;
    } else {
        // 如果没有找到空格,则整个字符串都是第一个单词
        count = s.length();
    }
    
    cout << count << endl; // 输出结果到标准输出
    return 0; // main 函数应该返回 0
}

两种另外的方法,我个人更喜欢第二种,find方法,简洁明了还好理解,但是这个npos是第一次接触。

空字符通常用 \0 表示,是一个 ASCII 值为 0 的字符,它在 C 和 C++ 中用于标记字符串的结束。字符串在内存中以空字符结尾,因此当处理字符串时,一旦遇到空字符,就知道字符串结束了。

而 npos 是 C++ std::string 类中的一个特殊常量,它表示一个不存在的位置。npos 通常被设置为 size_t 类型的最大可能值,这意味着它远远大于任何字符串的实际长度。在 std::string 类的搜索函数(如 findrfindfind_first_offind_first_not_of 等)中,如果没有找到搜索的子字符串或字符,这些函数会返回 npos

全部评论

相关推荐

刷牛客的我很豁达:你是不是对算法有什么误解,你没手握两篇顶刊顶会,还想搞算法岗,有顶刊顶会在算法岗算才入门
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务