easy 最后一个单词的长度 istringstream

在这里插入图片描述


暴力搜索

c++:


class Solution {
public:
    int lengthOfLastWord(string s) {
        int count = 0;  // 计数非空格字符
        for(int i=s.size()-1; i>=0; i--){
            if(s[i]!=' '){
                count++;
                //continue;   // 结束该次 for 循环,继续下次for循环
            }else if(s[i]==' ' && count !=0 ){
                break; // 结束整个 for 循环
            }
            // 遇到结尾连空格,什么都不执行,继续下一次for循环
        }
        return count;
    }
};

python


class Solution:
    def lengthOfLastWord(self, s: str) -> int:

        count = 0
        for i in range(len(s)-1,-1,-1):  # 从右到左遍历区间,左闭右开,每次-1
            if s[i]!=' ':
                count +=1
            elif s[i]==' ' and count != 0:
                break
        return count


使用函数:

c++ :istringstream 函数


class Solution {
public:
 假如有一行用空格隔开的字符串的话,如何提取出每一个字符串
    int lengthOfLastWord(string s) 
    {
        istringstream in(s);   创建istringstream对象in, 并同时使in和字符串s绑定
        string res;
        while(in>>res);   // 将从s中读取到的字符串in写入到字符串res
        return res.size();
    }
};

python: strip 函数


class Solution:
    def lengthOfLastWord(self, s: str) -> int:

        return len(s.strip().split(' ')[-1])
        #  strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
        # [-1] 取最后一个
        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想要从istringstream对象中获取固定长度的字符,可以使用`readsome`或`getline`函数。 1. readsome函数 readsome函数从流中读取指定数量的字符,不像`getline`函数那样读取整行。它的语法如下: ``` streamsize readsome (char* s, streamsize n); ``` 其中,第一个参数s是一个字符数组,用于存储读取的字符;第二个参数n是要读取的字符数量。readsome函数返回实际读取的字符数量,这个数量可能小于指定的数量n。 以下是一个示例代码: ``` #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string str = "abcdefghijk"; istringstream iss(str); char buf[5]; while (iss.readsome(buf, 5)) { cout.write(buf, iss.gcount()); } return 0; } ``` 输出结果为: ``` abcde fghij k ``` 在上面的示例中,我们定义了一个字符串变量str,它包含了要处理的字符串。然后,我们定义了一个istringstream对象iss,并将str作为参数传入。接着,我们定义了一个大小为5的字符数组buf,用于存储读取的字符。在while循环中,我们使用readsome函数从istringstream对象中读取5个字符,并将它们存储到buf数组中。最后,我们使用cout.write函数将读取的字符打印出来。 2. getline函数 getline函数从流中读取一行字符,并将其存储到一个字符串中。它的语法如下: ``` istream& getline (istream& is, string& str, char delim); ``` 其中,第一个参数is是输入流对象;第二个参数str是要存储读取的字符串;第三个参数delim是行结束符。如果指定了行结束符,getline函数将会读取到行结束符为止;否则,它将读取到输入流的末尾为止。 以下是一个示例代码: ``` #include <iostream> #include <sstream> #include <string> using namespace std; int main() { string str = "abcdefghijk"; istringstream iss(str); string line; while (getline(iss, line, '\n')) { cout << line << endl; } return 0; } ``` 输出结果为: ``` abcdefghijk ``` 在上面的示例中,我们定义了一个字符串变量str,它包含了要处理的字符串。然后,我们定义了一个istringstream对象iss,并将str作为参数传入。接着,我们定义了一个字符串变量line,用于存储读取的一行字符。在while循环中,我们使用getline函数从istringstream对象中读取一行字符,并将其存储到line字符串中。最后,我们打印出line字符串。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值