Str. substr (startpos, length );
Startpos is the sequence number of the starting character, and length is the string length (including
Startpos ).
Str. substr (m, n-m );
# Include <string>
# Include <iostream>
Using namespace std;
Main ()
{
String s ("12345 asdf ");
String a = s. substr (0th); // obtain a string of 4 characters starting from characters in string s.
Cout <a <endl;
}
Output result:
1234
Start and end of search character
# Include <iostream>
Using std: cout;
Using std: endl;
# Include <string>
Using std: string;
Int main ()
{
String s1 ("AA1234567890asdfasdf ");
String s2 ("AAB ");
String s3;
// Test substr "to-end-of-string" option
Cout <"The substring of s1 starting atn"
<"Location 5, s1.substr (5), is: n"
<S1.substr (5) <endl;
Return 0;
}
/*
The substring of s1 starting
Location 5, s1.substr (5), is:
4567890 asdfasdf
Find the location of a character
# Include <iostream>
Using std: cout;
Using std: endl;
# Include <string>
Using std: string;
Int main ()
{
String s1 ("AA1234567890asdfasdf ");
String s2 ("AAB ");
String s3;
// Test string member function substr
Cout <"The substring of s1 starting at location 0 forn"
<"14 characters, s1.substr (0, 14), is: n"
<S1.substr (0, 14) <"nn ";
Return 0;
}
How to Use the substr function to obtain the file extension
# Include <iostream>
# Include <string>
Using namespace std;
Int main (int argc, char * argv [])
{
String filename, basename, extname, tmpname;
Const string suffix ("tmp ");
/* For each command-line argument
* (Which is an ordinary C-string)
*/
For (int I = 1; I <argc; ++ I ){
// Process argument as file name
Filename = argv [I];
// Search period in file name
String: size_type idx = filename. find ('.');
If (idx = string: npos ){
// File name does not contain any period
Tmpname = filename + '.' + suffix;
}
Else {
/* Split file name into base name and extension
*-Base name contains all characters before the period
*-Extension contains all characters after the period
*/
Basename = filename. substr (0, idx );
Extname = filename. substr (idx + 1 );
If (extname. empty ()){
// Contains period but no extension: append tmp
Tmpname = filename;
Tmpname + = suffix;
}
Else if (extname = suffix ){
// Replace extension tmp with xxx
Tmpname = filename;
Tmpname. replace (idx + 1, extname. size (), "xxx ");
}
Else {
// Replace any extension with tmp
Tmpname = filename;
Tmpname. replace (idx + 1, string: npos, suffix );
}
}
// Print file name and temporary name
Cout <filename <"=>" <tmpname <endl;
}