#include <iostream>
#include <string>
using namespace std;
int main(){
string word = "abcdefg";
long long a = word.find("abc"); // 찾음
if(a == string::npos) // npos는 못찾았을때 리턴하는 long long 형변수의 쓰레기값이다.
{
cout << "못찾음" << endl;
}
else
{
cout << "찾음" << endl;
}
a = word.find("xyz"); // 못찾음
if(a == string::npos)
{
cout << "못찾음" << endl;
}
else
{
cout << "찾음" << endl;
}
}
#include <iostream>
#include <string>
using namespace std;
int main(){
string word = "abcdefg";
cout << word + "hijk" << endl;
// 결과 : abcdefghijk
}
#include <iostream>
#include <string>
using namespace std;
int main(){
string word = "abcdefg";
word.erase(0, 3);
//word.erase(0); // => 결과 : ""(해당 인데스부터 전부 삭제)
cout << word << endl;
// 결과 : defg
}
관련 참고 : https://modoocode.com/240
실수형도 가능 이 경우 stof, stod
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "1234";
string intToString;
int num = 4567;
int strToInt;
intToString = to_string(num);
strToInt = stoi(str);
cout << strToInt << endl;
cout << intToString << endl;
결과 : 1234
4567
}
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "ABC";
string str2 = "def";
for(int i = 0; i < str.size(); i++)
{
str[i] = tolower(str[i]);
str2[i] = toupper(str2[i]);
}
cout << str << str2 << endl;
// 결과 : abcDEF
}
replace() : a 위치부터 b위치까지 문자열을 다른 문자열로 바꾼다.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello";
str.replace(str.find("Hello"), str.size(), "Hi");
cout << str << endl;
}
regex_replace : 문자열에서 특정문자열을 찾아 원하는 문자열로 전부 바꾼다.
#include <regex> 필요
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
string str = "Name my john Is";
str = regex_replace(str, regex("Name"), "My");
str = regex_replace(str, regex("my"), "name");
str = regex_replace(str, regex("john"), "is");
str = regex_replace(str, regex("Is"), "John");
cout << str << endl;
string str2 = "aabbaaccaaddaa";
str2 = regex_replace(str2, regex("a"), "o");
cout << str2 << endl;
}
// 결과 : My name is John
: oobbooccooddoo
숫자이면 true반환, 숫자가 아니라면 false반환
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "1a2b3c4d5f";
for(int i = 0; i < str.size(); i++)
{
if(isdigit(str[i]))
cout << str[i] << ": 숫자입니다." << endl;
if(isalpha(str[i]))
cout << str[i] << ": 알파벳입니다." << endl;
}
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "aBcD";
cout << "대문자인가? : ";
for(int i = 0; i < str.length(); i++)
if(isupper(str[i]))
cout << str[i];
cout << endl << "소문자인가? : ";
for(int i = 0; i < str.length(); i++)
if(islower(str[i]))
cout << str[i];
}
// 결과 :
// 대문자인가? : BD
// 소문자인가? : ac