Getting the first 3 characters in C | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Getting the first 3 characters in C

Hi, I wanna know if I have to use strcpy for getting the first 3 characters of a string ? Is there another way to do it or no ?

14th Nov 2021, 11:55 AM
Marzieh NOROUZI
Marzieh NOROUZI - avatar
8 Answers
+ 3
Considering you only want to copy 2 characters from source string, it's better to use strncpy() cause it allows us to specify how many characters are to be copied over. https://code.sololearn.com/cgj5BzZ6DIzu/?ref=app (Edited)
14th Nov 2021, 1:18 PM
Ipang
+ 1
IMHO it's simplest to use strcpy() or strncpy(), cause those functions were meant for that purpose exactly. You can write your own, but that would probably be against the code-reuse concept.
14th Nov 2021, 12:59 PM
Ipang
+ 1
Awe thank you so much , and also for getting the last two characters we have to use strcpy ? I've written this ,it works but I'm not sure if this is the optimized or no ? Int main() { Char mot[5],mot_trois_der[3]; Printf(" entrez votre mot : "); Gets(mot); Strcpy (mot_trois_der,mot); Printf("%s",mot); Printf("\n"); Return 0; }
14th Nov 2021, 1:06 PM
Marzieh NOROUZI
Marzieh NOROUZI - avatar
+ 1
Awe thanks so much , you rock ! 🤘
14th Nov 2021, 1:32 PM
Marzieh NOROUZI
Marzieh NOROUZI - avatar
+ 1
Wait a minute, did you mean to copy first 2 characters or last 2 characters ... I had to ask cause your original post mentioned "first 3 character" in the title ...
14th Nov 2021, 1:34 PM
Ipang
+ 1
The last 2 characters 😬
14th Nov 2021, 1:46 PM
Marzieh NOROUZI
Marzieh NOROUZI - avatar
+ 1
Okay, I have updated my response with a code bit ...
14th Nov 2021, 2:19 PM
Ipang
+ 1
Ah you're so kind , thank you so so much !!
14th Nov 2021, 2:40 PM
Marzieh NOROUZI
Marzieh NOROUZI - avatar