문자열 - 문자배열

reference

문자열은 C++ string 객체를 사용하거나 문자 배열로 표시한다. 문자 배열을 사용 시 배열 이름은 포인터 상수이므로 상수로 선언한다.

실수 2개의 값을 변경하는 코드를 참조자를 사용해 구현한 코드이다.

실습 예제

ch04ex2_stringcat.cpp

두 문자열을 연결하여 첫 문자열에 대입하는 stringcat 함수를 포인터로 구현한 코드 이다. 선언부에서 두번째 멤버 변수에 const 키워드는 코드 중 변경되지 않는 상수처럼 사용된다는 의미이다.

#define _CRT_SECURE_NO_WARNINGS 
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

void stringcat(char* p_str1, const char* p_str2);

int main()
{
	char str1[20] = "Hello";
	char str2[10] = "world";
	stringcat(str1, str2);
	cout << "str1: " << str1 << endl;

	return 0;
}

void stringcat(char* p_str1, const char* p_str2)
{
	int idx = 0;
	for (int i = 0; p_str1[i] != '\0'; i++, idx++);
	for (int i = 0; p_str2[i] != '\0'; i++)
	{
		p_str1[idx++] = p_str2[i];
	}
	p_str1[idx] = '\0';
}

ch04ex3_stringswap.cpp

두 문자열을 교환하는 stringswap 함수를 구현한 코드이다.

실습 문제

ch04lab3_stringadd.cpp

두 문자열 st1, st2와 두 문자열을 더한 문자열을 대입할 st3을 인수로 보내면, st3의 문자열을 반환하는 함수를 구현하시오.

Last updated