문자열은 문자들의 배열입니다

 

문자열은 컴퓨터 메모리 구조상에서 마지막에 널(NULL) 값을 포함합니다

널(NULL) 값은 문자열의 끝을 알리는 목적으로 사용됩니다

그러므로 printf() 함수를 실행하면 컴퓨터는 내부적으로 NULL을 만날때까지 출력합니다

 

C언어에서 문자열배열이므로 포인터 형태로 사용할 수 있습니다

 

문자열을 활용한 간단한 예시

1
2
3
4
5
6
7
8
#include <stdio.h>
 
int main(void) {
    char* a = "Hello World";
    printf("%s\n", a);
    system("pause");
    return 0;
}
cs

 

하나의 문자열 안의 글자수를 세는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//하나의 문자열 안의 글자수 세기
int main(void){
    char input[1001];
    gets(input);
    int count = 0;
    while (input[count] != '\0') {
        count++;
    }
    printf("입력한 문자열의 길이는 %d\n", count);
    printf("입력한 문자는 %s",input);
    return 0;
}
cs

 

문자열 입출력 함수 예시

1
2
3
4
5
6
7
8
9
10
11
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void) {
    char a[100];
    gets_s(a, sizeof(a));
    printf("%s\n", a);
    system("pause");
    return 0;
}
 
cs

위와 같이 gets_s()를 이용하는 경우 범위를 넘으면 런타임(Runtime)오류가 발생하게 됩니다

 

 

문자열 처리를 위한 다양한 함수

  • strlen()   문자열의 길이를 반환합니다
  • strcmp()   문자열 1이 문자열 2보다 사전적으로 앞에 있으면 -1,뒤에 있으면 1을 반환
  • strcpy()   문자열을 복사합니다
  • strcat()   문자열 1에 문자열 2를 더합니다
  • strstr()   문자열 1에 문자열 2가 어떻게 포함되어 있는지를 반환합니다

 

strlen()를 활용한 예시

1
2
3
4
5
6
7
8
9
#include <stdio.h>
#include <string.h>
 
int main(void) {
    char inputOne[5= "A";
    char inputTwo[5= "B";
    printf("문자열 비교 : %d\n", strcmp(inputOne,inputTwo));
    return 0;
}
cs

inputOne 이 inputTwo 보다사전적으로 앞에 있기 때문에 -1을 반환합니다

 

 

strlen()를 활용한 예시 2

1
2
3
4
5
6
7
8
9
#include <stdio.h>
 
int main(void) {
    char a[20= "Byeonghak Jang";
    printf("문자열의 길이: %d\n", strlen(a));
    system("pause");
    return 0;
}
 
cs

 

1
2
3
4
5
6
7
8
#include <stdio.h>
#include <string.h>
 
int main(void) {
    char input[5= "LOVE";
    printf("문자열의 길이 : %d\n", strlen(input));
    return 0;
}
cs

 

strcmp()를 활용한 예시

 

 

strcmp()를 활용한 예시2

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
 
int main(void) {
    char a[20= "Byeonghak Jang";
    char b[20= "Hojjon Seok";
    printf("두 배열의 사전순 비교: %d\n", strcmp(a, b));
    system("pause");
    return 0;
}
 
cs

왼쪽에 있는 문자열이 사전적으로 앞에 있으므로 -1 을 반환합니다

 

 

strcpy()를 활용한 예시

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
 
int main(void) {
    char a[20= "My Name";
    char b[20= "Byeonghak Jang";
    strcpy(a, b);
    printf("복사된 문자열: %s\n", a);
    system("pause");
    return 0;
}
 
cs

 

strcat()를 활용한 예시

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
 
int main(void) {
    char a[30= "My Name is ";
    char b[20= "Byeonghak Jang";
    strcat(a, b);
    printf("합쳐진 결과 문자열: %s\n", a);
    system("pause");
    return 0;
}
 
cs

두 문자열을 합치기 때문에 글자 수를 char a[20] 에서 char a[30] 으로 늘렸습니다

 

strstr()를 활용한 예시

1
2
3
4
5
6
7
8
9
#include <stdio.h>
 
int main(void) {
    char a[20= "I like you";
    char b[20= "like";
    printf("찾은 문자열: %s\n", strstr(a, b));
    system("pause");
    return 0;
}
cs

실행하게 되면 like부터 찾은 이후의 모든 문자열을 반환하게 되므로 like you 가 반환됩니다

 

'C' 카테고리의 다른 글

다차원 배열과 포인터 배열  (0) 2021.02.10
C언어에서 변수를 처리하는 방법  (0) 2021.02.10
문자 : 아스키 코드(Ascii Code) , 버퍼(Buffer)  (0) 2021.02.08
포인터  (0) 2021.02.08
배열  (0) 2021.02.08

아스키 코드

C 프로그램의 문자는 아스키 코드를 따릅니다

아스키 코드는 0~127중 1바이트로 구성되며 주요 문자를 출력하도록 해줍니다

 

0 의 아스키 코드는 48

A 의 아스키 코드는 65

a 의 아스키 코드는 97

 

아스키 코드 출력 예시

1
2
3
4
5
6
7
8
9
#include <stdio.h>
 
int main(void) {
    char a = 65;
    printf("%c\n", a);
    system("pause");
    return 0;
}
 
cs

char a = 65; 를 활용하여 A를 출력 할 수 있습니다

 

버퍼

버퍼란 임시적으로 특정한 데이터를 저장하기 위한 목적으로 사용됩니다

문자열을 처리 할때 버퍼의 개념이 많이 사용됩니다

C 에서는 기본적으로 버프를 이용해 입출력을 처리합니다

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void) {
    int a;
    char c;
    scanf("%d"&a);
    printf("%d\n", a);
    int temp;
    while((temp = getchar()) !=EOF && temp !='\n'){}
    scanf("%c"&c);
    printf("%c\n", c);
    system("pause");
    return 0;
}
 
cs

while((temp = getchar()) !=EOF && temp !='\n'){} 를 활용하여 프로그램이 바로 종료되지 않고

scanf("%c"&c); 를 입력 받을 수 있습니다

 

만약 위의 while문을 사용하지 않으면 scanf("%d"&a); 에 문자입력 후 엔터를 입력하는 것이

scanf("%c"&c); 로 입력이되므로 프로그램이 바로 종료됩니다

 

'C' 카테고리의 다른 글

C언어에서 변수를 처리하는 방법  (0) 2021.02.10
문자열  (0) 2021.02.08
포인터  (0) 2021.02.08
배열  (0) 2021.02.08
함수  (0) 2021.02.08

포인터는 특이한 변수로 변수 자체가 존재하는 메모리 주소를 가집니다

 

 

  • 주소 연산자(&)   변수 앞에 붙어서 변수의 메모리 시작 주소 값을 구합니다

  • 포인터(*)   포인터 변수를 선언할 때 사용합니다

  • 간접 참조 연산자(*)  선언된 포인터 변수가 가리키는 변수를 구합니다

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
 
int main(void) {
    int a = 5;
    int* b = &a;
    printf("%d\n"*b);
    system("pause");
    return 0;
}
 
cs

int *b = %a; 에서의 *기호는 포인터

printf("%d\n", *b); 에서의 *기호는 간접 참조 연산자 입니다

 

 

배열 각 원소의 주소 값 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
 
int main(void) {
    int a[] = { 1,2,3,4,5,6,7,8,9,10 };
    int i;
    for (i = 0; i < 10; i++) {
        printf("%d\n"&a[i]);
    }
    system("pause");
    return 0;
}
 
 
cs

 

포인터를 활용해 두 변수의 값을 서로 변환하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//두 변수의 값을 변환하기
 
 
//두 변수의 값을 서로 변환하는 포인터 함수
void swap(int* x, int* y) {
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 
 
int main(void) {
    int x = 1;
    int y = 2;
    swap(&x, &y);
    printf("x = %d\ny = %d\n", x, y);
    return 0;
}
cs

 

예를 들어

int x = 70;

int *y = &x; 라는 변수가 있다면

 

y 는 주소값(ex)00AA00BB)를 가지고

*y 는 70을 가집니다

역시 x 또한 70 입니다

 

결과적으로

x == *y

&x == y

 

 

포인터 변수의 값을 바꾸는 예시

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
 
int main(void){
    int i = 10;
    int* p;
    p = &i;
    printf("i = %d\n", i);
    *= 20;
    printf("i = %d\n", i);
    return 0;
}
cs

 

'C' 카테고리의 다른 글

문자열  (0) 2021.02.08
문자 : 아스키 코드(Ascii Code) , 버퍼(Buffer)  (0) 2021.02.08
배열  (0) 2021.02.08
함수  (0) 2021.02.08
반복문  (0) 2021.02.08

배열을 사용하면 동일한 성격의 데이터를 다수 표현할 수 있습니다

 

 

배열을 활용한 예시

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
 
int main(void) {
    int a[10= { 6,5,4,3,9,8,0,1,2,7 };
    int i;
    for (i = 0; i < 10; i++) {
        printf("%d ", a[i]);
    }
    system("pause");
    return 0;
}
 
cs

 

 

배열의 원소 중에서 최댓값을 찾는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <limits.h>
 
int main(void) {
    int a[10= { 6,5,4,3,9,8,0,1,2,7 };
    int i, maxvalue = INT_MIN;
    for (i = 0; i < 10; i++) {
        if (maxvalue < a[i]) maxvalue = a[i];
    }
    printf("%d\n", maxvalue);
    system("pause");
    return 0;
}
 
cs

INT_MIN 은 최댓값을 구하기 위해 자주 사용되는 기능입니다

<limits.h>헤더파일에 정의가 되어 있는 것으로 int형 범위의 최솟값을 반환합니다

 

배열의 원소 중에서 최댓값과 최솟값의 위치를 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#define _CRT_SECURE_NO_WARNINGS
#define NUMBER 5
#include <stdio.h>
#include <limits.h>
//5개의 정수중에서 최댓값과 최솟값의 위치를 출력하는 프로그램
 
 
int main(void) {
    int i, max, min, index;
    int array[NUMBER];
    max = 0;
    index = 0;
    // array [0] ~ array[4] : 총 5개가 들어갈 수 있는 크기의 배열 선언
    for (i = 0; i < NUMBER; i++) {
        scanf("%d"&array[i]);
        if (max < array[i]) {
            max = array[i];
            index = i;
        }
    }
    printf("가장 큰 값은 %d 입니다, 그리고 %d번째에 있습니다\n", max, index + 1);
    min = INT_MAX;
    for (i = 0; i < NUMBER; i++) {
        scanf("%d"&array[i]);
        if (min > array[i]) {
            min = array[i];
            index = i;
        }
    }
    printf("가장 작은 값은 %d 입니다, 그리고 %d번째에 있습니다\n", min, index + 1);
    return 0;
}
cs

 

정수중에 최댓값과 최솟값의 위치를 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NUMBER 5
 
int main(void) {
    int array[NUMBER];
    int i, oddMax, evenMax;
    oddMax = 0;
    evenMax = 0;
    for (i = 0; i < NUMBER; i++) {
        scanf("%d", &array[i]);
        if (array[i] % 2 == 0) {
            if (evenMax < array[i]) {
                evenMax = array[i];
            }
        }
        else {
            if (oddMax < array[i]) {
                oddMax = array[i];
            }
        }
    }
    printf("%d %d", oddMax, evenMax);
    return 0;
}
cs

 

문자열과 배열의 예시

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
 
int main(void) {
    char a[20= "Hello World";
    a[4= ',';
    printf("%s\n", a);
    system("pause");
    return 0;
}
 
cs

a[4]와 같이 특정한 index에 접근해서 값을 변경할 수 있습니다

 

문자열에 포함된 'l' 의 개수 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void) {
    char a[] = "Hello World";
    int count = 0;
    for (int i = 0; i <= 10; i++) {
        if (a[i] == 'l') count++;
    }
    printf("%d\n", count);
    
    system("pause");
    return 0;
}
 
cs

 

 

'C' 카테고리의 다른 글

문자 : 아스키 코드(Ascii Code) , 버퍼(Buffer)  (0) 2021.02.08
포인터  (0) 2021.02.08
함수  (0) 2021.02.08
반복문  (0) 2021.02.08
조건문  (0) 2021.02.08

함수는 입력을 받아 처리한 뒤에 출력하는 구조를 가집니다

 

함수는 소스코드가 반복되는 것을 줄이도록 해줍니다

 

 

반환 자료형 함수명(매개변수){

 

              return 반환할 값;

}

 

 

함수를 활용해 특정한 말머리를 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
 
void dice(int input) {
    printf("던진 주사위: %d\n", input);
}
 
int main(void) {
    dice(3);
    dice(5);
    dice(1);
    system("pause");
    return 0;
}
 
cs

 

함수를 활용해 더하기를 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
 
int add(int a, int b) {
    return a + b;
}
 
int main(void) {
    printf("%d\n", add(1020));
    printf("%d\n", add(50-30));
    printf("%d\n", add(70125));
    system("pause");
    return 0;
}
 
cs

 

함수를 활용해 사칙연산을 출력하는 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
 
void calculator(int a, int b) {
    printf("%d + %d = %d\n", a, b, a + b);
    printf("%d - %d = %d\n", a, b, a - b);
    printf("%d * %d = %d\n", a, b, a * b);
    printf("%d / %d = %d\n", a, b, a / b);
    printf("\n");
}
 
int main(void) {
    calculator(103);
    calculator(152);
    calculator(184);
    system("pause");
    return 0;
}
 
cs

 

함수를 활용하면 보다 깔끔하고 간결한 프로그래밍이 가능합니다

 

 

재귀 함수

자기 자신을 포함하는 함수입니다

반드시 재귀 종료 조건이 필요합니다

 

 

재귀 함수를 이용한 팩토리얼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int factorial(int a) {
    if (a == 1return 1;
    else return a * factorial(a - 1);
}
 
int main(void) {
    int n;
    printf("n 팩토리얼을 계산합니다");
    scanf("%d"&n);
    printf("%d\n", factorial(n));
    system("pause");
    return 0;
}
 
cs

이때 무한 루프가 발생하지 않게 종료 조건을 잘 설정하는 것이 중요합니다

'C' 카테고리의 다른 글

포인터  (0) 2021.02.08
배열  (0) 2021.02.08
반복문  (0) 2021.02.08
조건문  (0) 2021.02.08
연산자  (0) 2021.02.08

+ Recent posts