c - 对结构成员的字符串操作

标签 c optimization string

根据我之前的帖子,我想出了以下代码。我确信有更好的方法来做到这一点。我想知道,那会是什么?

如果大于 max chars 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

最佳答案

好吧,我会好好研究一下。首先,让我说我的格式更改是为我准备的。如果你不喜欢孤独的{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 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;
}

最大的变化是我摆脱了你的strdup来电。相反,我将字符串直接填充到其目标缓冲区中。我还给 malloc 打了更多电话对于单个字符串缓冲区。这让您无法提前知道输入字符串的长度,代价是一些额外的分配。

关于c - 对结构成员的字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4207206/

相关文章:

Ruby 检查与 Rspec 中的 to_s

检查字符串是否包含另一个 C

c - 将字符串拆分为单词

C 编程 - 2U 和 1024U 大小

php - SQL执行时间太长

Java - StringIndexOutOfBoundsException 异常

c++ - 为什么具有引用指针的输入的函数无法编译?

objective-c - cocoa 编程在 C 中?

Python Scipy 优化 curve_fit

ruby - 我如何优化这段 ruby​​ 代码以使其运行得更快?