[英]c - string manipulation to struct member
Based on my previous post, I came up with the following code. 根据我以前的帖子,我提出了以下代码。 I'm sure there is a better way of doing it. 我确信有更好的方法。 I'm wondering, what would that be? 我想知道,那会是什么?
It does split the string if greater than max chars OR
if @ is found. 如果大于最大字符,则它会拆分字符串OR
如果找到@则拆分字符串。 Any ideas would be appreciated! 任何想法,将不胜感激!
#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;
}
Output at 5 chars max: 输出最多5个字符:
Hello
Worl
d
Foo B
ar In
here
Bar F
oo do
t com
here
there
Alright, I'll take a crack at it. 好吧,我会对它采取一些措施。 First, let me say that my formatting changes were for me. 首先,我要说我的格式更改对我而言。 If you don't like lonely {s, that's fine. 如果你不喜欢寂寞,那很好。
#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 World@Foo Bar In here@Bar Foo dot com@here@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;
}
The big change is that I got rid of your strdup
calls. 最大的变化是我摆脱了你的strdup
电话。 Instead, I stuffed the string directly into its destination buffer. 相反,我将字符串直接填充到其目标缓冲区中。 I also made more calls to malloc
for individual string buffers. 我还为单个字符串缓冲区调用了malloc
。 That lets you not know the length of the input string ahead of time at the cost of a few extra allocations. 这使得您无法提前知道输入字符串的长度,但需要花费一些额外的分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.