2014-02-10 3 views
-1

여러 문자열을 처리 할 함수로 읽으려고합니다. 명령은 각 문자열을 함수에 전달하는 것입니다 (2 차원 문자열 배열을 만들지 않음). 매개 변수는 동일하게 유지되어야합니다. 여기 내가 시도한 것입니다함수에 여러 문자열 전달

#include <stdio.h> 
#include <math.h> 

void convert(char s[]), int counts[]); 

int main(void) 
{ 
    int i = 0; 
    int d[2] = {}; 
    char text0[] = "this IS a String 4 you."; 
    char text1[] = "This sample has less than 987654321 leTTers."; 
    while(i<2) 
    { 
     convert (text[i],d); """ this is wrong but i dont know how to correctly do this 
     i = i +1; 
    } 

} 

void convert(char s[]), int counts[]) 
{ 

printf("%s this should print text1 and text2", s); 

} 

그래서 몇 가지 질문이 있습니다. 뭔가 특별한 문자/연산자가 파이썬에서 glob 모듈과 비슷하지만 정확하게 문자열을 읽을 때마다 convert (text[i],d) 부분을 수행 할 수 있습니까? 또한 int counts[] 목적은 함수의 단어 및 문자 수로 채워집니다. 그래서 나는 기능 convert이 배열을 작성하는 경우 것입니다 주요 내가 u는 "("에서 "무효 변환을 잃었 생각 convert

+0

'text0'과'text [0] '은 완전히 다른 변수입니다. –

+0

네, 그게 어디 붙어 있니. 나는 그런 식으로하고 싶지만 어떻게 잘 모르겠다. –

답변

0

의 실제 수를 반환하지 않고 main에 단어/문자 수를 인쇄해야하기 때문에 또한 그것을 인식 (char s []), int counts []); "를 참조하십시오. 그것은 무효가되어야한다 convert ((char s []), int counts []);

+1

너의 답변이 아니기 때문에, 제안은 사용자의 글에 댓글로 주어져야한다. –

+0

@MadHatter 아마도 그의 평판 점수로 인해 그를 코멘트에 게시 할 수 없습니다. http://stackoverflow.com/help/privileges/comment – nodakai

+0

@nodakai : Right !! 그것을 알지 못했 ... –

1

당신은 모든 문자열을 전달 임시 문자열 포인터 배열을 사용할 수 있습니다

char text1[] = "This sample has less than 987654321 leTTers."; 
    char const * texts[] = { text0, text1 }; 
    convert (texts, 2, d); 
} 

void convert(char const * s[], size_t n, int counts[]) 
{ 
    while(n--) { 
     *counts++ = strlen(*s); 
     printf("%s\n", *s++); 
    } 
} 

일부 노트 :

  1. 내가 인수 유형을 기능 char const을 추가했다. 함수가 문자열을 변경하지 않을 때 항상 그렇게해야합니다. 함수에서 문자열을 변경해야하는 경우 const 만 제거하면됩니다.
  2. 배열 배열 요소 수를 함수에 전달하는 추가 인수 size_t n이 있습니다. size_tstddef.h에서 찾을 수 있습니다.
0
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

void convert(char s[], int counts[]); 

int main(void){ 
    int i = 0; 
    int d[2] = {0}; 
    char text0[] = "this IS a String 4 you."; 
    char text1[] = "This sample has less than 987654321 leTTers."; 
    char *text[] = { text0, text1 }; 
    for(i=0; i<2; ++i){ 
     convert (text[i], d); 
     printf("%d, %d\n", d[0], d[1]); 
    } 

} 

void convert(char s[], int counts[]){ 
    printf("%s\n", s); 
    { 
     char *temp = strdup(s); 
     char *word, *delimiter = " \t\n";//Word that are separated by space character. 
     int count_w=0, max_len=0; 
     for(word = strtok(temp, delimiter); word ; word = strtok(NULL, delimiter)){ 
      int len = strlen(word); 
      if(max_len < len) 
       max_len = len; 
      ++count_w; 
     } 
     counts[0] = count_w; 
     counts[1] = max_len; 
     free(temp); 
    } 
} 
관련 문제