Getting a substring of a char* is a simple subject that may be simply completed. This can be utilized for a variety of programming duties similar to hacking, net crawling, and string manipulation. On this article I’ll talk about the essential idea and description the mandatory steps for acquiring a substring from a char*.
Nevertheless, earlier than transferring in the direction of the principle course of, let’s first perceive the idea of a substring.
What’s a Substring
A substring is barely a smaller string of the principle textual content. This smaller “portion” that’s being obtained should nonetheless include the unique character or characters from the unique string. For instance, if the unique string was “good day world”, then the substring could be “good day” or “world” relying on the specified output.
Get a Substring of a Char
The C customers can get a substring of a char by following capabilities:
1: strncpy() Perform
The primary approach to get a substring of a char* is to make use of the strncpy() C library operate. It copies a selected variety of characters from one string to a different. To switch a substring from a char* to a freshly constructed buffer, use this operate. Right here is an instance of the best way to use strncpy():
Right here, pos denotes the start index and len is the specified substring’s size.
#embrace <string.h>
int fundamental()
{
int pos, len;
char str[14] = “abcdefghijklm”;
char substring[14];
pos = 6;
len = 5;
printf(“Authentic string is: %s “, str);
printf(“nsubstring is: “);
strncpy(substring,str+(pos-1),len);
printf(substring);
return 0;
}
On this instance, substring is the vacation spot buffer, char str is the supply string and pos is 6 which implies string slicing will begin from sixth place (f) and ends on the fifth worth, which is j within the case. This can end in a substring buffer of the primary 50 characters from the unique char* copied from.
Output
2: substr() Perform
The second approach to get a substring of a char* is to make use of the substr() C library operate. It’s used to extract a piece of a string primarily based on the beginning index and variety of characters. This operate can be utilized to return a pointer to the substring or to change the present string. An instance of substr() utilization is the next:
#embrace <stdlib.h>
char* substr(const char *src, int m, int n)
{
int len = n-m;
char *dest = (char*)malloc(sizeof(char)*(len + 1));
for (int i=m; i<n && (*(src+i) != ‘