C++中的子串

在C++中,STD::SUBLUTE()是用于字符串处理的预定义函数。 一串H 是字符串函数所需的头文件。 这个函数有两个值 销售时点情报系统 伦恩 并返回一个新构造的字符串对象,其值初始化为该对象子字符串的副本。字符串的复制从 销售时点情报系统 直到 pos+len 方法 [pos,pos+len) . 要点:

null
  1. 第一个字符的索引是0(不是1)。
  2. 如果 销售时点情报系统 等于字符串长度,则函数返回空字符串。
  3. 如果 销售时点情报系统 大于字符串长度,则抛出_范围之外的_。如果发生这种情况,字符串中不会有任何更改。
  4. 如果请求的子字符串 伦恩 大于字符串的大小,则返回的子字符串为 [pos,size()) .
  5. 如果 伦恩 未作为参数传递,则返回的子字符串为 [pos,size()。

语法:

string substr (size_t pos, size_t len) const;Parameters:pos: Position of the first character to be copied.len: Length of the sub-string.size_t: It is an unsigned integral type.Return value: It returns a string object.

CPP

// CPP program to illustrate substr()
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
// Take any string
string s1 = "Geeks" ;
// Copy three characters of s1 (starting
// from position 1)
string r = s1.substr(1, 3);
// prints the result
cout << "String is: " << r;
return 0;
}


输出:

String is: eek

应用:

  1. 如何在字符后获取子字符串? 在这种情况下,一个字符串和一个字符是给定的,您必须打印子字符串,后跟给定的字符。 在测试结束后提取所有内容 “:” 在弦中 “狗:猫” .

C++

// CPP program to illustrate substr()
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
// Take any string
string s = "dog:cat" ;
// Find position of ':' using find()
int pos = s.find( ":" );
// Copy substring after pos
string sub = s.substr(pos + 1);
// prints the result
cout << "String is: " << sub;
return 0;
}


输出

String is: cat

2. 如何获得 字符前的子字符串? 在这种情况下,一个字符串和一个字符是给定的,您必须打印子字符串,后跟给定的字符。 提取字符串“dog:cat”中“:”之前的所有内容。

CPP

// CPP program to illustrate substr()
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
// Take any string
string s = "dog:cat" ;
// Find position of ':' using find()
int pos = s.find( ":" );
// Copy substring before pos
string sub = s.substr(0 , pos);
// prints the result
cout << "String is: " << sub;
return 0;
}


输出

String is: dog

3. 打印给定字符串的所有子字符串 4. 表示数字的字符串的所有子字符串之和

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享