String 기본 개념

--·2022년 6월 23일
0

cin vs getline

cin : 버퍼에 \n 남아있다
getline : \n 제외하고 n-1개의 문자열 저장

#include <iostream>
using namespace std;


int main() {
	char a[100], b[100], c[100];

	cin >> a;
	cin.getline(b, 100);
	cin.getline(c, 100);
	cout << "a:" << a << endl;
	cout << "b:" << b << endl;
	cout << "c:" << c << endl;
	return 0;
}

입력

aaa -> enter -> bbb -> enter -> ccc -> enter

출력

a : aaa
b : bbb
c : ccc
출력일 것 같지만
a : aaa
b :
c : bbb 이 출력된다

왜냐하면 cin에 \n가 남아 있기 때문에 cin.ignore()로 버퍼의 \n을 제거해야 한다.

#include <iostream>
using namespace std;


int main() {
	char a[100], b[100], c[100];

	cin >> a;
	cin.ignore();
	cin.getline(b, 100);
	cin.getline(c, 100);
	cout << "a:" << a << endl;
	cout << "b:" << b << endl;
	cout << "c:" << c << endl;
	return 0;
}

cin의 경우(cin은 공백 무시)

#include <iostream>
using namespace std;


int main() {
	char a[100], b[100], c[100];

	cin >> a;
	cin >> b;	
	cin >> c;	
	cout << "a:" << a << endl;
	cout << "b:" << b << endl;
	cout << "c:" << c << endl;
	return 0;
}

입력 aaa bbb ccc
출력
a : aaa
b : bbb
c : ccc


getline 함수의 두가지 종류

1. cin.getline

char*형의 문자열받을 경우 사용!
이때, 마지막 칸은 '\n'을 위해 남겨둔다.

예를들어 0,1,2,3,4,5,6,7,8,9를 입력했다면 0부터 8까지만 저장이 되고 마지막 test[9]에는 '\n'이 들어가는 것이다.

char형 대신 string형을 사용한다면 오류가 발생한다.

#include <iostream>
using namespace std;
int main(){
  char test[10];
  cin.getline(test,10);
  cout << test << endl;
  return 0;
}

2. getline (string)

cin.getline과 달리 string 문자를 입력 받을 때 사용

헤더파일 #include <string>

  #include <iostream>
#include <string>
using namespace std;
int main(){
    string test;
    getline(cin,test);
    cout << test << endl;
    return 0;}

replace(), find() 사용하기

1. replace()

#include <iostream>
#include <string>
using namespace std;

int main() {
	string input = "abcccc";
	string order = "sss";
	cout << "Before " << input << endl;
	input.replace(2, 3, order);
	cout << "After " << input << endl;

	return 0;
}

출력창

문자열.replace(시작 index, 치환 문자열 길이, 치환할 문자열)

2. find()

#include <iostream>
using namespace std;


int main() {
	string str1 = "abcde";

	cout << str1.find("a") << endl; // 0
	cout << str1.find("b") << endl; // 1
	cout << str1.find("c") << endl; // 2
	cout << str1.find("abc") << endl; // 0
	cout << str1.find("z") << endl; // 4294967295

	if (str1.find("z") == string::npos) {
		cout << "검색 문자열이 없습니다." << endl; // 문자열을 찾지 못했을 경우.
	}

	return 0;
}

find()함수는 문자열의 인덱스 값을 리턴해주고
없으면 npos 리턴

0개의 댓글