Skip to content

Instantly share code, notes, and snippets.

@seong-min-s
Last active August 29, 2019 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seong-min-s/ac154fc6512d7c43b12f20ffc0a91345 to your computer and use it in GitHub Desktop.
Save seong-min-s/ac154fc6512d7c43b12f20ffc0a91345 to your computer and use it in GitHub Desktop.
string 함수 정리
// 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;
}
// 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;
}
// 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;
}
@seong-min-s
Copy link
Author

seong-min-s commented Aug 29, 2019

c_str

string->char*

const char* c_str() const noexcept;

compare

비교하려는 대상 그대로 비교, 비교하는 문자열 또는 비교 대상 문자열 내의 문자열 비교, string과 char형과 비교

string
int compare (const string& str) const noexcept;
substring
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen = npos) const;
c_string
int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
buffer
int compare (size_t pos, size_t len, const char* s, size_t n) const;

@seong-min-s
Copy link
Author

substr

데이터의 내부 문자열을 가져온다.

string substr (size_t pos = 0, size_t len = npos) const;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment