Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a part of a string (substring) in C

Tags:

c

I have a string:

char * someString; 

If I want the first five letters of this string and want to set it to otherString, how would I do it?

like image 562
SuperString Avatar asked Jan 22 '10 01:01

SuperString


People also ask

How can I copy just a portion of a string in C?

We can use string function strncpy() to copy part strings. Part of the second string is added to the first string. strcpy(destination_string, source_string, n);

How do I copy part of a string to another?

Just add your offset to the str1 argument of the strncpy call. For example: strncpy(str2, str1 + 1, 5); will copy five bytes into str2 from str1 starting at index 1.

How do you take a specific part of a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do I copy one part of a string to another in C++?

The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object.


1 Answers

#include <string.h> ... char otherString[6]; // note 6, not 5, there's one there for the null terminator ... strncpy(otherString, someString, 5); otherString[5] = '\0'; // place the null terminator 
like image 106
pib Avatar answered Sep 20 '22 15:09

pib