Home > Software design >  How do I copy characters from one string to another string?
How do I copy characters from one string to another string?

Time:12-01

I have a problem, I am programming in C and it turns out that I am copying some characters from one string to another but I do it manually, you know with a function that it creates, but I want to know if there is any standard C function that allows me to do that, I will put An example so you can understand what I'm trying to say:

char str1[] = "123copy321";
char str2[5];

theFunctionINeed(str1, str2, 3, 6);   //Copy from str1[3] to str1[6]

printf("%s\n", str1);
printf("%s\n", str2);

and the result would be:

123copy321
copy

I hope you can help me, thank you

CodePudding user response:

You can use pointer arithmetic and the function memcpy:

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

int main( void )
{
    char str1[] = "123copy321";
    char str2[5];

    //copy str1[3] up to and including str1[6] to str2
    memcpy( str2, str1   3, 4 );

    //add terminating null character to str2
    str2[4] = '\0';

    printf( "%s\n", str1 );
    printf( "%s\n", str2 );
}

This program has the following output:

123copy321
copy

CodePudding user response:

With theFunctionINeed(str1, str2, 3, 6); there are a number of issues:

  1. Source string may be less than 3.

  2. Available sub-string length may be less than 4.

  3. Destination array may be too small.

  4. Unusual to pass in the first and last index to copy. This prevents forming a zero-length sub-string. More idiomatic to pass in beginning and 1) length or 2) index of one-past.

  5. How about returning something useful, like was the destination big enough?

Alternative untested sample code follows. restrict means the two pointers should not point to overlapping memory.

#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

// Return `destination` when large enough
// otherwise return NULL when `size` was too small. 
bool SubString(size_t destination_size, char *restrict destination,
    const char *restrict source, size_t offset, size_t length) {
  if (destination_size == 0) {
    return NULL;
  }
  destination[0] = '\0';

  // Quickly search for the null character among the first `offset` characters of the source.
  if (memchr(source, '\0', offset)) {
    return destination;
  }

  destination_size--;
  size_t destination_length = length <= destination_size ? length : destination_size;
  strncat(destination, source   offset, destination_length);
  return length <= destination_size ? destination : NULL;
}
  •  Tags:  
  • c
  • Related