当前位置: 动力学知识库 > 问答 > 编程问答 >

How to retrieve multiple substrings of a string and write them into one string in C?

问题描述:

How can I split a const char * string in the fastest possible way.

char *inputStr="abcde";

char buff[500];

I would like to have in buffer the following formatted string, format of which must be:

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

I'm learning C and new to the language. I have no clue where to start on this splitting problem.

网友答案:

I don't think you can do this particularly "fast", it seems like it's quite heavily limited since it needs to iterate over the source string many times.

I'd do something like:

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';
}

Note that this doesn't protect against buffer overrun in the output.

网友答案:

You could use strcpy, strcat/strncat and a simple loop:

#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;
}

outputs the desired IN('a','ab','abc','abcd','abcde')

网友答案:

To give you a start, consider the following code:

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);
}

The above code should print

i = 1, buffer = "a"
i = 2, buffer = "ab"
i = 3, buffer = "abc"
i = 4, buffer = "abcd"
i = 5, buffer = "abcde"
网友答案:

If you are looking for something like this in 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;
}

Output - a,ab,abc,abcd,abcde

分享给朋友:
您可能感兴趣的文章:
随机阅读: