Last active
August 29, 2019 11:48
-
-
Save seong-min-s/ac154fc6512d7c43b12f20ffc0a91345 to your computer and use it in GitHub Desktop.
string 함수 정리
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// strings and c-strings | |
#include <iostream> | |
#include <cstring> | |
#include <string> | |
int main () | |
{ | |
std::string str ("Please split this sentence into tokens"); | |
char * cstr = new char [str.length()+1]; | |
std::strcpy (cstr, str.c_str()); | |
// cstr now contains a c-string copy of str | |
char * p = std::strtok (cstr," "); | |
while (p!=0) | |
{ | |
std::cout << p << '\n'; | |
p = std::strtok(NULL," "); | |
} | |
delete[] cstr; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// comparing apples with apples | |
#include <iostream> | |
#include <string> | |
int main () | |
{ | |
std::string str1 ("green apple"); | |
std::string str2 ("red apple"); | |
if (str1.compare(str2) != 0) | |
std::cout << str1 << " is not " << str2 << '\n'; | |
if (str1.compare(6,5,"apple") == 0) | |
std::cout << "still, " << str1 << " is an apple\n"; | |
if (str2.compare(str2.size()-5,5,"apple") == 0) | |
std::cout << "and " << str2 << " is also an apple\n"; | |
if (str1.compare(6,5,str2,4,5) == 0) | |
std::cout << "therefore, both are apples\n"; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// string::substr | |
#include <iostream> | |
#include <string> | |
int main () | |
{ | |
std::string str="We think in generalities, but we live in details."; | |
// (quoting Alfred N. Whitehead) | |
std::string str2 = str.substr (3,5); // "think" | |
std::size_t pos = str.find("live"); // position of "live" in str | |
std::string str3 = str.substr (pos); // get from "live" to the end | |
std::cout << str2 << ' ' << str3 << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
substr
string substr (size_t pos = 0, size_t len = npos) const;