2010-11-17 95 views
3

基於我以前的文章,我想出了以下代碼。我相信有一個更好的方法來做到這一點。我想知道,那會是什麼?c - 字符串處理結構成員

如果發現@,它會在大於最大字符的情況下分割字符串OR。任何想法,將不勝感激!

#define _GNU_SOURCE 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

struct my_struct { 
    char *str; 
}; 

int main() { 
    struct my_struct *struc; 

    int max = 5; 
    char *tmp = "Hello [email protected] Bar In [email protected] Foo dot [email protected]@there"; 

    struc = malloc (20 * sizeof (struct my_struct)); 

    int strIdx = 0, offSet = 0; 
    char *p = tmp; 
    char *tmpChar = malloc (strlen (tmp) + 1), *save; 
    save = tmpChar; 

    while (*p != '\0') { 
    if (offSet < max) {    
     offSet++; 
     if (*p == '@') { 
     if (offSet != 1) { 
      *tmpChar = '\0'; 
      struc[strIdx++].str = strndup (save, max); 
      save = tmpChar; 
     } 
     offSet = 0; 
     } else 
     *tmpChar++ = *p; 
    } else {     // max 
     offSet = 0; 
     *tmpChar = '\0'; 
     struc[strIdx++].str = strndup (save, max); 
     save = tmpChar; 
     continue; 
    } 
    p++; 
    } 
    struc[strIdx++].str = strndup (save, max); // last 'save' 

    for (strIdx = 0; strIdx < 11; strIdx++) 
    printf ("%s\n", struc[strIdx].str); 

    for (strIdx = 0; strIdx < 11; strIdx++) 
    free (struc[strIdx].str); 
    free (struc); 
    return 0; 
} 

輸出在5個字符最大:

Hello 
Worl 
d 
Foo B 
ar In 
here 
Bar F 
oo do 
t com 
here 
there 
+0

一個評論(作爲評論):像'i','j','p','c','ss'和's'這樣的名稱並不使讀代碼更容易。如果'j'確實是'抵消',那麼稱之爲。它看起來像'i'是你的結構數組的索引。 'string_idx','strIdx',甚至'idx'會更有意義。 – nmichaels 2010-11-17 17:48:47

+0

@Nathon:感謝您的觀察,我已經使它更易讀:) – Mike 2010-11-17 18:08:16

回答

1

好吧,我帶你去一個裂縫它。首先,讓我說我的格式更改適合我。如果你不喜歡孤獨{s,那很好。

#define _GNU_SOURCE 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define MAX 5 

struct string_bin 
{ 
    char *str; 
}; 


int main() 
{ 
    struct string_bin *strings; 

    char *tmp = "Hello [email protected] Bar In [email protected] Foo dot [email protected]@there"; 

    char *p = tmp; 
    strings = malloc (20 * sizeof (struct string_bin)); 
    memset(strings, 0, 20 * sizeof (struct string_bin)); 

    int strIdx = 0, offset = 0; 
    char *cursor, *save; 

    strings[strIdx].str = malloc(MAX+1); 
    save = strings[strIdx].str; 
    while (*p != '\0') 
    { 
     if (offset < MAX && *p != '@') 
     { 
      *(save++) = *(p++); 
      offset++; 
      continue; 
     } 
     else if (*p == '@') 
      *p++; 
     offset = 0; 
     *save = '\0'; 
     strings[++strIdx].str = malloc(MAX+1); 
     save = strings[strIdx].str; 
    } 
    *save = '\0'; 

    for (strIdx = 0; strings[strIdx].str != NULL; strIdx++) 
    { 
     printf ("%s\n", strings[strIdx].str); 
     free (strings[strIdx].str); 
    } 

    free (strings); 

    return 0; 
} 

最大的變化就是我擺脫了你的strdup電話。相反,我將字符串直接填充到目標緩衝區中。我還爲個別字符串緩衝區撥打了更多電話malloc。這可以讓你不必知道輸入字符串的長度,但需要花費額外的分配。

+0

我喜歡你的方法來擺脫strdup調用。謝謝! – Mike 2010-11-17 18:58:19