Zacky112
Zacky112

Reputation: 8879

Transform an array of integers into a string

A function returns an aray of integers and I want it to pass to another function which searches for some pattern. But the second function expects a string.

Example:

int IArray = {1, 2, 3};
// should be coverted into "123"

Is there a direct function available? If not, how do I convert the array of integers into a string?

Upvotes: 1

Views: 8936

Answers (6)

user82238
user82238

Reputation:

int IArray = {1, 2, 3};

That's not C!

Do you mean;

int IArray[3] = {1, 2, 3};

You could do this...

for( loop = 0 ; loop < 3 ; loop++ )
  *(((char *) IArray)+loop) = '0' + IArray[loop];

*(((char *) IArray)+loop) = 0;

printf( "%s\n", (char *) IArray );

...but I wouldn't if I were you :-)

Upvotes: 0

Roger Pate
Roger Pate

Reputation:

There is nothing in the C stdlib to do this, but it isn't hard to write the string manipulations:

#include <assert.h>

int transform_ints_to_string(int const* data, int data_length,
                             char* output, int output_length)
{
  // if not enough space was available, returns -1
  // otherwise returns the number of characters written to
  // output, not counting the additional null character

  // precondition: non-null pointers
  assert(data);
  assert(output);
  // precondition: valid data length
  assert(data_length >= 0);
  // precondition: output has room for null
  assert(output_length >= 1);

  int written = 0;
  for (; data_length; data_length--) {
    int length = snprintf(output, output_length, "%d", *data++);
    if (length >= output_length) {
      // not enough space
      return -1;
    }
    written += length;
    output += length;
    output_length -= length;
  }
  return written;
}

Example:

int main() {
  char buf[100] = "";
  int data[] = {1, 2, 3};
  if (transform_ints_to_string(data, 3, buf, sizeof buf) == -1) {
    puts("not enough room");
  }
  else {
    printf("%s\n", buf);
  }
  return 0;
}

Upvotes: 2

Alok Singhal
Alok Singhal

Reputation: 96131

If your IArray variable contains integer values in the range [0,9], then you can do something like this (pseudocode):

string := ""
While more numbers:
    string.append(next + '0')

In C, it is guaranteed that '0', '1', ..., '9' have consecutive integral values.

If this is not what you want, you need to define your problem more clearly.

Upvotes: 0

Yin Zhu
Yin Zhu

Reputation: 17119

most c and c++ compilers support itoa function, which converts an int to a char*, or you can use sprintf to do this. The next thing is to concatenate all strings into a single string, you can use strcat . Follow the links, you will find examples for these two functions.

Upvotes: 1

Sphinx
Sphinx

Reputation: 311

Is there a direct function available I can use?

NO

Upvotes: 1

codaddict
codaddict

Reputation: 455000

There is no direct function to do that.

You'll have to use sprintf.

Upvotes: 5

Related Questions