0

如何const char *以最快的方式拆分字符串。

char *inputStr="abcde";
char buff[500];

我想在缓冲区中有以下格式化字符串,其格式必须是:

IN('a','ab','abc','abcd','abcde')

我正在学习 C 和语言新手。我不知道从哪里开始解决这个分裂问题。

4

4 回答 4

0

我认为你不能特别“快速”地做到这一点,它似乎受到了很大的限制,因为它需要多次迭代源字符串。

我会做类似的事情:

void permute(char *out, const char *in)
{
  const size_t in_len = strlen(in);
  char *put;

  strcpy(out, "IN(");
  put = out + 3;
  for(i = 1; i < in_len; ++i)
  {
    if(i > 1)
     *put++ = ',';
    *put++ = '\'';
    memcpy(put, in, i);
    put += i;
    *put++ = '\'';
  }
  *put++ = ')';
  *put++ = '\0';
}

请注意,这不能防止输出中的缓冲区溢出。

于 2013-10-23T07:47:27.177 回答
0

首先,请考虑以下代码:

char buffer[64];
const char str[] = "abcde";

for (size_t i = 1; i <= strlen(str); ++i)
{
    strncpy(buffer, str, i);
    buffer[i] = '\0';  /* Make sure string is terminated */
    printf("i = %lu, buffer = \"%s\"\n", i, buffer);
}

上面的代码应该打印

i = 1,缓冲区 = "a"
i = 2,缓冲区 =“ab”
i = 3,缓冲区 =“abc”
我= 4,缓冲区=“abcd”
i = 5,缓冲区 =“abcde”
于 2013-10-23T07:48:08.230 回答
0

您可以使用strcpy, strcat/strncat和一个简单的循环:

#include <stdio.h>
#include <string.h>

int main(void) {
    char* inputStr = "abcde";
    char buff[500];
    // start the formatted string:
    strcpy(buff,"IN(");
    int i, len = strlen(inputStr);
    for (i = 0; i < len; ++i) {
        strcat(buff, "'");
        strncat(buff, inputStr, i + 1);
        strcat(buff, "'");
        // if it is not last token:
        if (i != len - 1)
            strcat(buff, ",");
    }
    // end the formatted string:
    strcat(buff,")");
    printf("%s", buff);
    return 0;
}

输出所需的IN('a','ab','abc','abcd','abcde')

于 2013-10-23T07:49:20.720 回答
0

如果您正在 C++ 中寻找类似的东西:-

#include <iostream>
#include <string.h>

using namespace std;

int main() {

    const char *inputStr = "abcde"; //const to remove warning of deprecated conversion
    char buff[500];

    int count = 0;

    for (int i = 0; i < (int) strlen(inputStr); i++) {   //cast it to int to remove 
                                   // warning of comparison between signed and unsigned
        for (int j = 0; j <= i; j++) {
            buff[count++] = inputStr[j];
        }
        buff[count++] = ',';
    }
    buff[--count] = '\0';
    cout << buff;
    return 0;
}

输出 - a,ab,abc,abcd,abcde

于 2013-10-23T07:59:37.203 回答