Can anyone please help me.I want to remove character from char*
in C.
For example, char *str
this str equals to "apple" and first i remove 1. character and define a new variable then remove 2. character and define new variable and so on until the str ends.
How can ı do that ? I'm completely new to C, and just can't seem to figure it out
CodePudding user response:
Assuming you only need to remove characters from the left.
Because strings in C are arrays of characters, and arrays are pointers to the first element of the array, you can create variables that point to specific indices in you original char array.
For example
char* myString = "apple";
char* subString = myString 1;
printf("%s\n%s\n", myString, substring);
would produce the output
apple
pple
We could generalize this to store all substrings obtained by removing characters from the left in an array of char*
pointers (pointers to pointers). Like so:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** GetSubStrings(char* input)
{
int length = strlen(input);
char** result = calloc(length, sizeof(char*));
for(int i = 0; i < length; i )
{
result[i] = input i;
}
return result;
}
int main()
{
char* myString = "apple";
char** subStrings = GetSubStrings(myString);
for(int i = 0; i < strlen(myString); i )
{
printf("%s\n", subStrings[i]);
}
free(subStrings);
return 0;
}