String

hy cho·2021년 12월 25일
0

알고리즘 공부

목록 보기
18/26
post-thumbnail

파싱 - 필요한 정보만 빼오는 것

string 클래스 - 문자열을 다루는 클래스이다.

기존 두 문자열 비교
char arr[10] = "asdf";
char brr[10] = "asdd";
if (strcmp(arr, brr) == 0) cout << "같은 문자열";
else cout << "다른 문자열";

string클래스 사용으로 비교

string str1 = "asdf";
string str2 = "asdf";

if (str1 == str2)
{
	cout << "같은 문자열";
}
else
{
	cout << "다른 문자열";
}

더욱 편리하게 비교할 수 있어진다.

string 문자열의 길이 구하기
string str = "asdf";

int str_len = str.length();
cout << str_len;

============================================
스트링으로 문자열 입력받아 거꾸로 출력

string str;
cin >> str;
int len = str.length();

for (int i = len - 1; i >= 0; i--)
{
	cout << str[i];
}

===================================================

스트링으로 아이디 비번 입력받아 일치하는지 판단

#include
#include

using namespace std;
int main()
{
string id1 = "kevin";
string pw1 = "850715";
string id2;
string pw2;
int cnt = 0;

cin >> id2 >> pw2;

if (id1 == id2)
{
	
	cnt++;
}
else
{
	cout << "아이디 틀림";
}

if (pw1 == pw2)
{
	
	cnt++;
}
else
{
	cout << "비밀번호 틀림";
}

if (cnt == 2)
{
	cout << "로그인 성공";
}
return 0;

}

===========================================

5개 카드로 2개 골라 단어 완성시키기
starbuckskorea만드는 경우의 수

#include
#include

using namespace std;
int main()
{
string vect[5] = { "star", "start", "buckskorea", "starbucks", "korea" };
int cnt = 0;

for (int y = 0; y < 5; y++)
{


for (int x = 0; x < 5; x++)
{
	string cmp = vect[y] + vect[x];
	if (cmp == "starbuckskorea")
	{
		cnt++;
	}
}
}


cout << cnt;
return 0;

}

==================================================

정수열 - > 스트링으로 변환

int num = 1231;
string str = to_string(num);

스트링 - > 정수열 변환

string num = "486";
int kfc = stoi(num);

string str = "adfasZzdcfasdcfZsafd";
//대문자 Z 찾기

int index = str.find('Z', 0);
//찾는값이 없으면 -1 반환함

=============================================

문장 내에 sk라는 문자가 몇개 있는지 찾기

#include
#include

using namespace std;
int main()
{
string str;
cin >> str;
int cnt = 0;
int index = 0;

while (1)
{
	int ret = str.find("sk", index);
	if(ret == -1) break;
	cnt++;
	index = ret + 1;

}

	cout << cnt;
return 0;

}

필요한 부분만 추출

string str = "asdfkfcfd";
string result = str.substr(4, 3); //4번 인덱스부터 3개 빼감
kfc만 출력됨

===========================================
문자열 입력받아서 [HAHAHA] 부분을 찾고 그 안 부분만 출력하기

#include
#include

using namespace std;
int main()
{

string str;
cin >> str;

int index = str.find('[', 0);
int index2 = str.find(']', 0);
string result = str.substr(index+1, index2 -index -1 );

cout << result;
return 0;

}

================================================

#include
#include
using namespace std;
int main()
{
// []안의 글자만 출력하기
/*
1. a 찾기- [

2 b 찾기 -]

3 . substr

4.  출력

5. a= b+1; 그다음 [를 찾는 것


*/

string arr = "KS[486]GS[LG]SKC[KEVIN]T";
int a = 0;
int b;
while (1)
{
	a = arr.find('[', a);
	if (a == -1)break;
	b = arr.find(']', a + 1);
	string result = arr.substr(a + 1, b - a - 1);
	cout << result<<endl;
	a = b + 1;

}

return 0;

}

profile
hihi

0개의 댓글