C++ - string 문자열
1. C++ String
문자열 (C style vs. C++ style)
문자열 입력
2차원 char 배열과 포인터 배열
문자열 관련 함수C++ 11
- 문자열
- C style
- C++ Style
- string has a constructor that actually takes in char pointer or const char pointer.
- So, when compiling above code in visual studio and move the cursor to "Hello World3", we can check the above code is actually compiled as (const char[13]"Hello World3").
- null termination : we can check end point of string by the null termination. string data starts from the name of the array(memory address of the array). and it ends at null termination point.
- 문자열 입력
- char 데이터 입력
- %s : (argument type - char*)공백문자가 나오는 부분까지 입력받음.
- If width specifier is used, matches up to width or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters)
- (C++) 문자열을 입력받는 방법
- string 입력
- 공백, 띄어쓰기를 무시하고 입력받는방법
- scanf() 접근지정자 활용 - "%[^\n]" : \n (enter key) 까지 입력받음
- getline() - 공백, 띄어쓰기를 무시하고 ‘\n’까지의 string데이터를 input으로 받음
- 2차원 char 배열과 포인터 배열
- 2차원 char 배열 2차원 배열은 1차원 배열을 배열 요소로 갖는 새로운 배열이다.
- 2차원 배열을 선언할 때 크기를 생략하고 싶다면 첫번째 부분배열의 요소의 개수를 표기하는 부분을 생략함
- 행첨자 생략 가능
- 열 첨자는 생략 불가능
- 여러 개의 문자열을 저장하기 위해서는 2차원 문자배열이 필요
- 포인터 배열
- 포인터 배열은 포인터 변수들을 배열요소로 갖는 배열이다.
- 모든 배열 요소가 포인터 변수가된다.
- from C++11 string library string Header
- stoi() - converts a string to a signed integer
- to_string() - converts an integral or floating point value to string
- copy() - copies characters
- rbegin() - returns a reverse iterator to the beginning
- rend() - returns a reverse iterator to the end
#include <stdio.h>
int main()
{
char name1[6] = { 'h','e','l','l','o', '\0' };
const char name2[] = "Hello World1!";
const char* name3 = "Hello World2!";
return 0;
}
#include <iostream>
#include <string> //string 헤더 파일
int main()
{
std::string name4 = "Hello World3";
return 0;
}
char s [LENGTH];
scanf("%s", s);
std::string name1;
//scanf("%s", &str);
std::getline(std::cin, name1);
std::string name2
cin >> name2;
char line1[100];
scanf("%[^\n]",line1);
string line2;
getline(cin, line2);
char dataset[][7] = {"apple", "banana", "cocoa"};
int numArr[3][4] = { // 세로 크기 3, 가로 크기 4인 int형 2차원 배열 선언
{ 11, 22, 33, 44 },
{ 55, 66, 77, 88 },
{ 99, 110, 121, 132 }
};
char animal [][10] = { "monkey", "elephant", "dog", "sheep", "pig",
"lion", "tiger", "puma", "turtle", "fox" };
int count=sizeof(animal)/sizeof(animal[0]);
printf("%d\n", sizeof(animal)); //100
printf("%d\n", sizeof(animal[0])); //10
for(int i=0; i<count; i++)
{
printf("%s\n", animal[i]);
}
-
sizeof(animal) 전체 배열의 크기
sizeof(animal[0]) 부분배열 하나의 크기
animal[i] i 값이 변하면서 각각의 부분배열 명이 된다
char animal [5][10] = { "monkey", "elephant", "dog", "sheep", "pig" };
for(int i=0; i<5; i++)
{
printf("%s\n", animal[i]);
}
char* animal_ptr[5] = { "monkey", "elephant", "dog", "sheep", "pig" };
for(int i=0; i<5; i++)
{
printf("%s\n", *(animal_ptr + i));
}