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
一個評論(作爲評論):像'i','j','p','c','ss'和's'這樣的名稱並不使讀代碼更容易。如果'j'確實是'抵消',那麼稱之爲。它看起來像'i'是你的結構數組的索引。 'string_idx','strIdx',甚至'idx'會更有意義。 – nmichaels 2010-11-17 17:48:47
@Nathon:感謝您的觀察,我已經使它更易讀:) – Mike 2010-11-17 18:08:16