如何检索字符串的多个子字符串并将它们写入C中的一个字符串?

时间:2013-10-23 07:37:28

标签: c string pointers formatting string-formatting

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

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

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

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

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

4 个答案:

答案 0 :(得分: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';
}

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

答案 1 :(得分: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, buffer = "a"
i = 2, buffer = "ab"
i = 3, buffer = "abc"
i = 4, buffer = "abcd"
i = 5, buffer = "abcde"

答案 2 :(得分:0)

您可以使用strcpystrcat/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')

答案 3 :(得分: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