-1

I have a string

str = "hello"

I want to make a new string which is the first two digits of str "he".

How do I do this in C?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Aza
  • 45
  • 8
  • 1
    Have a look at this: https://www.tutorialspoint.com/c_standard_library/c_function_strncpy.htm – izlin Jun 22 '18 at 09:41
  • See strcpy(). Just type `man strcpy`. – Joy Allen Jun 22 '18 at 09:41
  • 1
    @JoyAllen `strcpy` copies the whole string. The OP only wants a part of the string so `strncpy` is the better fit. – izlin Jun 22 '18 at 09:44
  • If you're on Windows, use strncpy_s instead of strncpy. – ImmortaleVBR Jun 22 '18 at 09:54
  • 1
    I have been sitting in front of my pc for over 8 hours now today i'm very new and just trying to understand the cryptic C manuals is a challenge. I came here to try and get something in simple english because I'm struggling as I couldn't understand others I already viewed on stackoverflow. Thanks for your assistance – Aza Jun 22 '18 at 09:56
  • Happy that you managed to find your way @Aza, and welcome to Stackoverflow! Please notice for the next time you post a question, you should be posting what you have tried so far as well. Cheers! – gsamaras Jun 22 '18 at 10:01
  • It is only a small part of a large problem I am trying to solve but i'll be sure to remember. The crowd here can be pretty harsh I have found. – Aza Jun 22 '18 at 10:04

1 Answers1

1

Use strncpy(), like this:

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

int main(void) {
    char src[] = "hello";
    char dest[3]; // Two characters plus the null terminator

    strncpy(dest, &src[0], 2); // Copy two chars, starting from first character
    dest[2] = '\0';

    printf("%s\n", dest);
    return 0;
}

Output:

he

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    Original Poster didn't clarify as to whether he was after a cross-platform solution or for a specific OS, however if he/she is developing for Windows (and using an MS compiler), strncpy_s is the way to go over strncpy. The reason strncpy_s is technically safer than strncpy is because you have to specify the buffer size of the destination, and thus you'll be a tad less vulnerable to potential Buffer Overflow if the routine is used correctly. As a side note, if I recall correctly, strncpy_s should actually handle the null terminator for you as well. – ImmortaleVBR Jun 22 '18 at 09:58