题解 | #截取字符串#

截取字符串

https://www.nowcoder.com/practice/a30bbc1a0aca4c27b86dd88868de4a4a

#include <iostream>
#include <string>    // 仅包含需要的头文件
#include <stdexcept> // 包含标准异常处理

using namespace std;

int main() {
    string inputString; // 更具描述性的变量名
    int substringLength;

    cin >> inputString; // 读取字符串

    cin >> substringLength; // 读取整数

    try {
        // 检查substringLength是否大于字符串长度
        if (substringLength > inputString.length()) {
            throw out_of_range("The specified length exceeds the string length.");
        }
        cout << inputString.substr(0, substringLength) << endl; // 输出子字符串
    } catch (const out_of_range& e) {
        cerr << "Error: " << e.what() << endl; // 错误处理
    }

    return 0;
}

全部评论

相关推荐

06-27 18:45
中山大学 Ruby
25届应届毕业生,来广州2个礼拜了,找不到工作,绝望了,太难过了…
应届想染班味:9爷找不到工作只能说明,太摆了或者太挑了。
点赞 评论 收藏
分享
程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 Java
一口洪烧肉:哈哈哈哈哈哈哈哈哈哈哈硬要啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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