2011-01-27 4 views
0

이곳은 새로운 프로그래밍입니다. 원하는 입력을 통해 문장을 나눌 수 있고 별도로 출력 할 수있는 함수를 작성해야합니다.기본 C 배열 기능

"Hello, How are you ..."와 같은 입력은 23 자이고 다른 입력은 숫자 "6"입니다.

따라서, 나는 "어떻게 당신이 ...하는"나는 배열을 사용하는 것이 가장 좋은 것입니다 생각

이 ... 그러나, 나는이 기능을 쓸 수 없습니다 "안녕하세요"로 인쇄 할합니다. 누군가가 나를 도울 수 있기를 바랍니다.

그런데 헤더 파일에 함수를 넣으려면 어떻게해야합니까?

고마워요 ... C의 모든 문자열의

+1

스택 오버플로에 오신 것을 환영합니다! 이전에 시도한 내용, 실행 한 문제 및 해결할 수있는 것에 대해 좀 더 구체적으로 설명 할 수 있습니까? – templatetypedef

+0

원하는 결과물을 더 잘 보여줄 수 있습니까? 예를 들어, "너 어떠니?" 새 줄에있어? 또는 따옴표로 묶인 문자열의 공백으로 구분 된 집합을 원하십니까? –

+0

메모리 주소를 가져 와서 인덱스와 오프셋을 출력하는 함수를 작성해야합니다. – Buckeye

답변

1

우선 이미 char의 배열 인 char *입니다 :

char *msg = "Hello, World!"; 
int i; 
for(i=0; i<strlen(msg); ++i) 
{ 
    char c = msg[i]; 
    // Do something 
} 

당신이 헤더 파일에 함수를 넣어하려는 경우 단지 inline

+3

기술적으로'char *'는 char 배열에 대한 포인터입니다. –

+0

'inline'이든 아니든 컴파일러는 최적화 설정에 따라 원하는대로 할 수 있습니다. –

+0

적어도'gcc'에서는 헤더 파일에 넣으려는 경우 함수를'inline'으로 정의해야했습니다. 최적화가 아닙니다. – Elalfer

2

먼저 split_string을 선언하는 헤더 파일로 정의하십시오. (당신이 프로그래밍에 새로운, 나는 상세한 주석을 넣어) : 사용

// test.c 

#include <stdio.h> 
#include <string.h> /* for strlen */ 
#include <stdlib.h> /* for atoi */ 
#include "split_string.h" 

int main (int argc, char** argv) 
{ 
    /* Pass the first and second commandline arguments to 
    split_string. Note that the second argument is converted to an 
    int by passing it to atoi. */ 
    split_string (argv[1], atoi (argv[2])); 
    return 0; 
} 

void split_string (const char* s, int split_at) 
{ 
    size_t i; 
    int j = 0; 
    size_t len = strlen (s); 

    for (i = 0; i < len; ++i) 
    { 
     /* If j has reached split_at, print a newline, i.e split the string. 
     Otherwise increment j, only if it is >= 0. Thus we can make sure 
     that the newline printed only once by setting j to -1. */ 
     if (j >= split_at) 
     { 
      printf ("\n"); 
      j = -1; 
     } 
     else 
     { 
      if (j >= 0) 
      ++j; 
     } 
     printf ("%c", s[i]); 
    } 
} 

당신은 컴파일하고 (당신에게 가정으로 프로그램을 실행할 수 있습니다

/* Always begin a header file with the "Include guard" so that 
    multiple inclusions of the same header file by different source files 
    will not cause "duplicate definition" errors at compile time. */ 
#ifndef _SPLIT_STRING_H_ 
#define _SPLIT_STRING_H_ 

/* Prints the string `s` on two lines by inserting the newline at `split_at`. 
void split_string (const char* s, int split_at); 

#endif 

다음 C 파일은 split_string을 사용한다 GNU C 컴파일러) :

$ gcc -o test test.c 
$ ./test "hello world" 5 
hello 
world