C++ string中substr用法

使用C++实现字符串截取
本文介绍如何利用C++标准库中的字符串方法substr来截取字符串,并通过一个具体示例进行展示。该示例演示了如何从一个给定的字符串中连续截取出多个子串。同时,还讨论了当指定的起始位置超出字符串长度时,程序会抛出异常的情况。

s.substr(star, length)是用来获取字符串s中的一段字串

Examp:s=“0123456789”;s.substr(2, 5)=“23456”;s.substr(0, 5)=“01234”;


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
{
        string s;
        while (cin >> s) {
                for (int i = 0; i < 5; i ++) {
                        cout << s.substr(i, 5) << endl;
                }
        }
}

输入asdfghjkl

结果为:

asdfg
sdfgh
dfghj
fghjk
ghjkl

输入asdfghj

结果为:

asdfg
sdfgh
dfghj
fghj
ghj

输入:as

结果为:

as

s

terminate called after throwing an instance of 'std::out_of_range'

  what():  basic_string::substr: __pos (which is 3) > this->size() (which is 2)

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值