在C++中实现字符串截取的方法

分类:知识百科 日期: 点击:0

有多种,比如使用字符串函数substr(),使用C语言中的字符串库函数strncpy()等。

1.使用字符串函数substr()

substr()函数是C++标准库中的字符串函数,可以实现字符串的截取。函数原型为:string substr (size_t pos = 0, size_t len = npos) const;其中pos是截取的起始位置,len是截取的长度,npos是string类中定义的一个常量,表示从pos开始到字符串末尾的长度。

#include 
#include 
using namespace std;

int main(void)
{
    string str = "Hello World";
    string str1 = str.substr(6, 5); //从第6个字符开始截取5个字符
    cout << str1 << endl;
    return 0;
}

运行结果:World

2.使用C语言中的字符串库函数strncpy()

strncpy()函数是C语言中的字符串库函数,可以实现字符串的截取。函数原型为:char *strncpy(char *dest, const char *src, size_t n);其中dest是指向目标字符串的指针,src是指向源字符串的指针,n是指定要拷贝的字符数。

#include 
#include 
using namespace std;

int main(void)
{
    char str[] = "Hello World";
    char str1[6];
    strncpy(str1, str+6, 5); //从第6个字符开始截取5个字符
    str1[5] = '\0'; //添加字符串结束符
    cout << str1 << endl;
    return 0;
}

运行结果:World

3.使用标准库提供的迭代器

在C++标准库中提供了迭代器的概念,可以使用迭代器实现字符串的截取。

#include 
#include 
using namespace std;

int main(void)
{
    string str = "Hello World";
    auto it = str.begin() + 6; //定义迭代器,指向第6个字符
    string str1(it, str.end()); //从迭代器it开始到字符串末尾
    cout << str1 << endl;
    return 0;
}

运行结果:World

以上介绍了C++中实现字符串截取的三种方法,分别是使用字符串函数substr()、使用C语言中的字符串库函数strncpy()以及使用标准库提供的迭代器。这三种方法都可以实现字符串的截取,根据实际情况选择合适的方法即可。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。