2012-01-02 4 views
1

のgcc 4.6.2 C89がこのSDP文字列から個々の要素を取得するための文字列を解析するための良い方法である場合、私はちょうど疑問に思って別の要素

に文字列を解析します。

これは文字列です:

"v=0\no=sjphone 853596844 1765236571 IN IP4 10.10.10.10\ns=-\nc=IN IP4 10.10.10.10\nt=0 0\nm=audio 19112 RTP/AVP 8\na=rtpmap:8 PCMA/8000\na=ptime:20\n" 

そして、私はこのようにそれを分けたい:

v=0 
o=sjphone 853596844 1765236571 IN IP4 10.10.10.10 
s=- 
c=IN IP4 10.10.10.10 
t=0 0 
m=audio 19112 RTP/AVP 8 
a=rtpmap:8 PCMA/8000 
a=ptime:20 

これは私のコードです:任意の提案のための

void parse_sdp_string(const char *sdp_string) 
{ 
#define MAX_NUM_ELEMENTS 16  
    char elements[MAX_NUM_ELEMENTS][MAX_STRING_LEN] = {{0}}; 
    apr_size_t element_count = 0; 
    apr_size_t i = 0; 
    apr_size_t k = 0; 

    char sdp_str[MAX_NUM_ELEMENTS * MAX_STRING_LEN] = {0}; 
    char *search_str = NULL; 

    /* Copy the string as to not corrupt the original */ 
    apr_cpystrn(sdp_str, sdp_string, sizeof sdp_str); 
    search_str = sdp_str; 

    /* Find the last carriage return to compare that we are at the last one */ 
    char *end_ptr = strrchr(search_str, '\n'); 

    /* Increment until you find a carriage return */ 
    while(*search_str != '\0') { 
     /* Fill the element in the array */ 
     elements[i][k++] = *search_str; 
     search_str++; 

     /* nul terminate and reset before starting copy next element */ 
     if(*search_str == '\n') { 
      elements[i][++k] = '\0'; 
      /* Next element */ 
      i++; 
      /* Set back to zero to copy from */ 
      k = 0; 

      /* Check that we are not at the last '\n' */ 
      if(search_str == end_ptr) { 
       /* This is the end, record the number of elements copied */ 
       element_count = i; 
       break; 
      } 

      /* skip over the current \n as we don't need to copy that */ 
      search_str++; 
     } 
    } 
} 

多くのおかげで、

+0

を#includeすることができますか? –

答えて

1

sscanf()を使用してください。 I = 25、X = 54.32E-1、名前= "ハムスター" になり

int i, n; 
float x; 
char name[50]; 
n = sscanf("25 54.32E-1 Hamster", "%d%f%s", &i, &x, name); 

:あなたのようなことを行うことができ、それによって

4

私は同意するrはstrtok()を使用しています。それはあなたに多くのコードを保存します。

1

strtokstrstrのような機能を使用すると、人生が楽になります。実際には、「検索」グループstring.hに属するほとんどのものを使用することができます。

関連する問題