[day7] 문자열

나는컴공생·2025년 3월 12일

취준

목록 보기
1/1

아스키 코드 (7bit)
'0' : 48
'A' : 65
'a' : 97
'\n': 10
'\r':

문자 0을 기준으로 적으면 연산자, 크면 숫자로 인식

한글 한자
euc.kr - 2byte
utf - 3byte

c

  • 배열 : 마지막에 구분자 '\0' 방식
    cpp : string
  • 객체 : 길이 방식(start로부터 얼마나)

c계열: 컴파일러가 2바이트씩 읽어서 알아서 잘 해준다.

문자열 관련 headers
#include : cpp string 객체
#include <string.h> : c의 string

atoi(문자열), atof: 표준함수
itoa: 비표준 리눅스, gcc에는 없음.

  
  #include <stdio.h>
//#include <string.h> // c 기반 문장려 : strlen 
#include <cstring> // string.h 확장버전
#include <cstdlib> //atoi, itoa(숫자 <-> 문자)
#include <iostream>
using namespace std;
int my_strlen(char* str) { //c는 1byte를 len 1로 생각(한글은 2byte)
	int len = 0;
	while (*str) { //현재 값을 찍을 때 * 사용, 마지막 문
		len++;
	}
	return len;
}
//long long - 64bit
//8, 10, 16 진법이 아닌 경우
void my_itoa(char* sNum, int val, int digit) {
	int idx = 0;
	if (val < 0) {
		sNum[0] = '-';
		idx++;
	}
	int iNum; char c;
	while (val) {
		iNum = iNum % digit;
		if (iNum < 10) { //0~9까지의 형태가 들어옴
			c = iNum + '0';
		}
		else {
			c = iNum + 'a' - 10;
		}
		char c = val % 10 + '0';
		sNum[idx++] = c;
		val = val / 10;
	}
	sNum[idx] = 0; //널문자 넣어주기
	//puts(sNum);
	//순서 반대로 바꿔줘야함(reverse)
	int len = idx / 2; //ex) len 4 -> 중앙 2 len 5 -> 중앙 2
	for (int i = 0; i < len; ++i) {
		char t = sNum[i];
		sNum[i] = sNum[idx - 1 -i]; //0번과 3번이랑 바꾸기
		sNum[idx - 1 - i] = t;
	}
}
void my_strcpy(char* dest, char* src) {
	while (*dest++ = *src++); //주소 복사시키고 ++로 이동
}
int main() {
	char buf3[100] = "123";
	char buf4[100];
	int iNum; double dNum = 1.234567;
	//scanf("%d", &iNum); //키보드로부터 읽어라
	sscanf(buf3, "%d", &iNum ); //배열로부터 읽어라
	cout << "iNum: " << iNum << "\n";
	sprintf(buf4, "%o", iNum); //배열에다가 뿌려라.
	puts(buf4);
	sprintf(buf4, "%x", iNum); //배열에다가 뿌려라.
	puts(buf4);
	sprintf(buf4, "%lf", dNum); //배열에다가 뿌려라.
	puts(buf4);
	char sNum[] = "123a";
	//숫자형 문자열 -> 숫자
	iNum = atoi(sNum); //"123"만 들어옴. 
	char buf2[100];
	itoa(iNum, buf2, 2);
	puts(buf2);

	char s[] = "hong";
	//string.h
	char s1[11] = "hong";
	char s2[11] = "aong";
	printf("len: %d\n", strlen(s1));
	//(a-b) > 0 : 1 : 앞선 문자열이 더 크다  / 0: 같다 / -1 : 뒤 문자열이 더 크다.
	printf("cmp: % d\n", strcmp(s2, s1));
	
	char buf[100] = "hong";
	//buf = s2 ; //error! (왜냐하면 buf는 배열이므로 주소를 바꿀 수 없음)
	strcpy(buf, s2); //초기화 다음 단계에서 어떤 문자열을 복사하려면 strcpy 사용해야함.
	strcat(buf, s2); //문자열 더하기

	char str1[11] = "hong"; //배열(배열 주소를 바꿀 수 없음: 상수)
	//char str2[11] = { 'h', 'o', 'n', 'g' };
	char str2[11]; 
	const char* str3 = "hong"; //포인터로 선언? 근데 이건 const이면,,, 바꿀 수없는거아님??

	str2[0] = 'h';
	str2[1] = 'o';
	str2[2] = '\0'; 
	printf("%s\n", str1);
	puts(str3);
	/*
		배열 
		- str1 = str2
		포인터는 자료형 동일하면 가능
		- str3 = str2 
	*/
	return 0;
}

#include <stdio.h>
#include <string>
#include <iostream> //cin, cout

using namespace std;

int main() {
	string str;
	cin >> str;
	cout << "str: " << str << endl;

	//file 종류 지점: -1로 끝남(EOF)
	while (getchar() != 10); //10 : '\n' 개행 (input 버퍼 비우는 코드)(실무에서)
	getline(cin, str);//현위치부터 개행 진적까지 모든 문자열 받기
	//c: gets , cpp: getline  -> buffer 비우기 작업 필요? 출력문 버퍼 비우기 (fflush) 
	cout << "str: " << str << endl;
	return 0;
}
#include <stdio.h>
#include <string>
#include <iostream> //cin, cout

using namespace std;

int main() {
	string s = "abcdefghij";

	//string -> arry
	char str[] = "hong";

	string str1 = "hong";
	string str2("hong");
	string str3 = str1; //기존 문자열 대입도 가능
	string str4 = str; //배열구조 넘겨주면 string으로 바뀜 
	//나중에 배열로 사용하고 싶으면 string.c_str() 사용
	string str5(str);


	char buf[100];
	strcpy(buf, str1.c_str());
	printf("str: %s\n", str); //ok
	//printf("str1: %s\n", str1);//error!
	printf("str1 : %s\n", str1.c_str()); // string에서 c 기반 배열주소로 사용하고 싶을때
	cout << "str : " << str << endl;
	cout << "str1 : " << str1 << endl;
}
 #include <stdio.h>
#include <string>
#include <iostream> //cin, cout

using namespace std;

int main() {
	string str = "abcdefghijde";
	printf("str[1]: %c\n", str[1]); //이게 더 속도 빠름
	printf("str[1]: %c\n", str.at(1));
	int idx = str.find("de"); //0번째 부터 "de"가 나타나는 첫번째 위치를 알려줌.
	printf("idx : %d\n", idx);
	idx = str.find("de", 5); //5번째 부터 "de"가 나타나는 첫번째 위치를 알려줌.
	printf("idx : %d\n", idx);
	//값이 존재하지 않으면 -1 반환
	idx = str.rfind("de"); //n-1번째부터 거꾸로 찾기
	printf("idx : %d\n", idx, 5);//5번째부터 에서 거꾸로 찾기
		
}
#include <stdio.h>
#include <string>
#include <iostream> //cin, cout
#include <vector>

using namespace std;

int main() {
	//: 기준으로 split하기
	vector<int> idxs;
	string str = "aaa:bbb:ccc:ddd";
	int idx = 0;
	
	while (1) {
		idx = str.find(":", idx);
		if (idx == -1) {
			break;
		}
		idxs.emplace_back(idx);
		idx++;
	}
	for (int& i : idxs) {
		printf("%d ", i);
	}puts("");

	string subString = str.substr(4); //이 5번(idx)부터 끝까지
	cout << subString << endl;
	subString = str.substr(4,3); //이 5번(idx)부터 3(크기)
	cout << subString << endl;
	subString = str.substr(4, 10000); //크기 초과해도 오류 안남
	cout << subString << endl;

}

cpp 에는 string reverse함수가 없다!
string +operator가 만들어져 있으므로 string 더하기 가능!

0개의 댓글