一、c截取字符串
c语言中可以使用strtok函数截取字符串,但是在c++中,可以使用string中的substr函数实现截取字符串。
substr函数接受两个参数,第一个参数为截取的起始下标,第二个参数为要截取的长度。如果只传入一个参数,则截取剩余的全部字符串。
#include
#include
using namespace std;
int main() {
string str = "hello world";
string sub_str = str.substr(6, 5);
cout << sub_str << endl; // "world"
return 0;
}
二、cstring截取字符串
cstring是c++中对于c语言中char*类型字符串的封装。使用cstring截取字符串可以使用类似于c语言中的指针进行截取。
可以通过对于字符串名的取地址,来获取字符串的首地址。利用指针可以直接操作字符串。
#include
#include
using namespace std;
int main() {
char str[] = "hello world";
char* sub_str = str + 6;
cout << sub_str << endl; // "world"
return 0;
}
三、截取字符串string
在string中截取字符串也可以使用substr函数,其实现方式与c截取字符串类似。
需要注意的是,在实际使用中,可以采用string对象的方式截取字符串。
#include
#include
using namespace std;
int main() {
string str = "hello world";
string sub_str = string(str, 6, 5);
cout << sub_str << endl; // "world"
return 0;
}
四、c截取字符串的指定字符
c语言中使用strchr函数来查找字符串中的指定字符,而在c++中可以使用find函数来实现。
find函数返回指定字符在字符串中第一次出现的位置。
#include
#include
using namespace std;
int main() {
string str = "hello world";
int index = str.find('w');
string sub_str = str.substr(index);
cout << sub_str << endl; // "world"
return 0;
}
五、std::string截取字符串
std::string和string的使用差不多,只是可能需要加上命名空间std::来使用。
std::string的substr函数用法和普通的string类似。
#include
#include
using namespace std;
int main() {
std::string str = "hello world";
std::string sub_str = str.substr(6, 5);
cout << sub_str << endl; // "world"
return 0;
}
六、string截取指定字符串
使用string的find函数获取子字符串在主字符串中的位置,再通过substr函数截取。
#include
#include
using namespace std;
int main() {
string str = "hello world";
string sub_str = "world";
int index = str.find(sub_str);
string result = str.substr(index);
cout << result << endl; // "world"
return 0;
}
七、string类型截取字符串
可以使用string的find函数和substr函数实现截取字符串。
#include
#include
using namespace std;
int main() {
string str = "hello world";
string sub_str = "wo";
int start = str.find(sub_str)+sub_str.size();
string result = str.substr(start);
cout << result << endl; // "rld"
return 0;
}
八、cstring截取到指定字符
和c语言中类似,使用strchr函数查找指定字符的位置,然后进行指针的操作实现字符串的截取。
#include
#include
using namespace std;
int main() {
char str[] = "hello, world";
char* sub_str = strchr(str, ',');
*sub_str = '\0';
cout << str << endl; // "hello"
return 0;
}
九、string截取两个字符串之间的值
可以使用string的find_first_of和find_last_of函数查找两个字符串的位置,然后通过substr函数进行截取。
#include
#include
using namespace std;
int main() {
string str = "hello world";
string start_str = "h";
string end_str = "d";
int start = str.find_first_of(start_str)+1;
int end = str.find_last_of(end_str);
string result = str.substr(start, end-start);
cout << result << endl; // "ello worl"
return 0;
}
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/242399.html
微信扫一扫
支付宝扫一扫