【发布时间】:2010-11-17 17:17:58
【问题描述】:
根据我之前的帖子,我想出了以下代码。我确信有更好的方法来做到这一点。我想知道,那会是什么?
如果找到@,它会在大于最大字符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 World@Foo Bar In here@Bar Foo dot com@here@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真的是offset,就这么称呼它。看起来i是您的结构数组的索引。string_idx,strIdx,甚至idx会更有意义。 -
@Nathon:感谢您的观察,我让它更具可读性:)
标签: c optimization string