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
Answer from Andreas Wenzel on Stack OverflowAre there better ways to copy one string to another?
copy character from string to another string in C - Stack Overflow
Copy string in C
How to copy from a string to another string in Java? - Stack Overflow
Videos
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
With theFunctionINeed(str1, str2, 3, 6); there are a number of issues:
Source string may be less than 3.
Available sub-string length may be less than 4.
Destination array may be too small.
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.
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;
}
Like an idiot, I was initially trying to copy all the elements of a string to another string the way one copies an array of int -
// both the strings str1 & str2 are of same length
for (int i = 0, n = strlen(str1); i < n; i++)
{
str2[i] = str1[i];
}And this was giving me a "Segmentation fault (core dumped)" every time I executed the program (compiling was okay). After scratching my head for sometime I decided to make str2 an array of chars.
char str2[26];
for (int i = 0, n = strlen(str1); i < n; i++)
{
str2[i] = str1[i];
}Voila! It is working perfectly. I just want to know why this segmentation fault happens in the first case. And if there are any better ways to copy strings. Now before someone suggests using "strcpy" from <string.h> , the same fault arises if you copy two strings & nothing goes wrong if str2 is made an array. So, yeah any explanations as to why this happens ? Thanks for reading my post.
First, you need add +1 in size for the \0.
char color1[3];
char color2[5];
and then:
strncpy(color1, string, 2);
color1[3] = '\0';
strncpy(color2, string + 2, 4);
color2[4] = '\0';
Assuming that
char *string = "AAbbCC";
printf("color1 => %s\ncolor2 => %s\n", color1, color2);
The output is:
color1 => AA
color2 => bbCC
I hope this help you.
UPDATE
You can write a substr() function to get part of string(from x to y) and then copy to your string.
char * substr(char * s, int x, int y)
{
char * ret = malloc(strlen(s) + 1);
char * p = ret;
char * q = &s[x];
assert(ret != NULL);
while(x < y)
{
*p++ = *q++;
x ++;
}
*p++ = '\0';
return ret;
}
Then:
char *string = "AAbbCC";
char color1[3];
char color2[4];
char color3[5];
char *c1 = substr(string,0,2);
char *c2 = substr(string,2,4);
char *c3 = substr(string,4,6);
strcpy(color1, c1);
strcpy(color2, c2);
strcpy(color3, c3);
printf("color1 => %s, color2 => %s, color3 => %s\n", color1, color2, color3);
The output:
color1 => AA, color2 => bb, color3 => CC
And Don't forget:
free(c1);
free(c2);
free(c3);
Well, color1 and color2 are two bytes long - you have no room for the \0 terminator. When you look at one of them as a string, you get more characters that you wished for. If you look at them as two characters, you'll get the right result.
You should define them as 3 characters long and put the \0 at the end.
A C string is a nul-terminated character array.
The C language does not allow assigning the contents of an array to another
array. As noted by Barry, you must copy the individual characters one by one
from the source array to the destination array. e.g. -
#define _CRT_SECURE_NO_WARNINGS
#include
#include
int main()
{
char str1[] = "Hello";
char str2[10] = {0};
for (int x = 0; x < strlen(str1); ++x)
{
str2[x] = str1[x];
}
printf("%s\n", str2);
return 0;
}
To make this common task easier there are standard library functions provided
which will perform this operation. e.g. - memcpy(), etc.
memcpy(str2, str1, 6);
When the array contains a nul-terminated string of characters you can use
strcpy(), etc.
strcpy(str2, str1);
Caveat: Some of the above functions are considered unsafe as they do not guard
against buffer overruns of the source and destination arrays. There are safer
versions provided by the compiler.
Note that if and when you start learning C++ you will find that there you can
assign a C++ std::string object to another object of the same type. However,
even in C++ the same rules apply when working with C strings, "raw" character
arrays, etc.
- Wayne
str2 is an array. It cannot appear on the left side of an assignment. You will need to use something like strcpy.
q is a pointer. It is perfectly legal to copy one pointer to another.
Use String.substring(...) if you only want some characters.
Edit:
To combine an existing string with some characters from another string you would use:
String anotherString = anotherString + originalString.substring(...);
To create a new string with some characters from another string you would use:
String aNewString = originalString.substring(...);
String objects are immutable, you can't modify them after they've been created. Instead you will have to use StringBuilder to make a new one by appending the charAt().