Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 308
  • Last Modified:

Is there a way to strcpy only part of a char array?

Hi all,

Is it possible to strcpy only part of the original char array into a new one? What I have in the code is my failed attempt to do so.
char hello[100] = "hello there";
char partOfHello[5];
 
strcpy (partOfHello, hello);

Open in new window

0
ehensens
Asked:
ehensens
  • 2
  • 2
1 Solution
 
ZoppoCommented:
Hi ehensens,

use 'strncpy' instead of 'strcpy', i.e.:

> strncpy( partOfHello, hello, 5 );

Hope that helps,

ZOPPO
0
 
ehensensAuthor Commented:
Thanks a lot.
0
 
Infinity08Commented:
Using strncpy like that is not enough, as in general you'll be left with a string that is not null-terminated.

If you need the first 5 characters of the 'hello' string, you'll need to allocate enough memory for 6 characters (the 5 characters + 1 for the '\0'), and explicitly set the '\0' :
char hello[100] = "hello there";
char partOfHello[6] = { 0 };        /* enough room for a string of length 5 */
 
strncpy(partOfHello, hello, 5);     /* copy 5 characters (or less if the original string is shorter) */
partOfHello[5] = '\0';              /* add the string null-terminator */

Open in new window

0
 
ehensensAuthor Commented:
Thank you Infinity08,

What I am doing is allocating more than I need for the new char array and then using strcmp to compare it to what I'm looking for.
0
 
Infinity08Commented:
>> and then using strcmp to compare it to what I'm looking for.

Maybe what you're really looking for is strncmp ?

        http://www.cplusplus.com/reference/clibrary/cstring/strncmp/

which compares only a given part (of a certain length) of the string.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now