본문 바로가기
C 언어

substr

by SpeeDr00t 2016. 7. 12.
반응형

substr( position, length ) : position으로 부터 lenght까지의 문자열 출력

1. test 소스 1

#include <stdio.h>

int main()
{
    char string[1000] = {"black falcon"};
    char sub[1000];
    int position = 7;
    int length = 6;
    int c = 0;

    while( c < length ) {

        sub[c] = string[position+c-1];
        c++;

    }
    sub[c] = '\0';

    printf(" substring is %s\n", sub );

    return 0;
}


결과

hacker@HACKER:~/c$ gcc -o substr substr.c

hacker@HACKER:~/c$ ./substr
 substring is falcon


2. test 소스 2

#include <stdio.h>
#include <stdlib.h>


char *c_substr(char *string, int position, int length)
{
   char *pointer;
   int c;

   pointer = malloc(length+1);

   if (pointer == NULL)
   {
      printf("Unable to allocate memory.\n");
      exit(1);
   }

   for (c = 0 ; c < length ; c++)
   {
      *(pointer+c) = *(string+position-1);
      string++;
   }

   *(pointer+c) = '\0';

   return pointer;
}

int main()
{
    char string[1000] = {"black falcon"};
    int position = 7;
    int length = 6;
    char *pointer;

    pointer = c_substr( string , position , length );
    printf(" substring is %s\n", pointer );
    free( pointer );


    return 0;
}

결과

gcc -o substr2 substr2.c

hacker@HACKER:~/c$ ./substr2
 substring is falcon
반응형

'C 언어' 카테고리의 다른 글

selection sort  (0) 2016.07.12
bubble sort  (0) 2016.07.12
enum  (0) 2016.07.12
file write  (0) 2016.07.12
switch  (0) 2016.07.12