I want to split an input array into three different ones based on a /
as a delimiter.
I have tried the (probably the naive) approach of storing an input string into different arrays by using getchar
and while
to read in the characters into an array and using a counter to count how many times a /
appears.
Based on this number I would use:
if (slashcounter == 0) {
destinationarray[i++] = c;
}
to store it into the proper array. full implementation below.
please note that I try to do this using only stdio.h
#include <stdio.h>
char c;
char replace[80], toBeReplaced[80], input[80], testInput[80];
int i = 0;
int slashcounter = 0;
int main(){
puts("Enter a line of text: ");
while (( c = getchar()) != '\n'){
if (c == '/') {
slashcounter++;
}
if (slashcounter == 0) {
replace[i++] = c;
}
else if (slashcounter == 1) {
toBeReplaced[i++] = c;
}
else if (slashcounter == 2) {
input[i++] = c;
}
}
//debug purpose
puts("The arrays have the following content\n");
puts("replace[]:\n");
puts(replace);
puts("\n");
puts("toBeReplaced[]:\n");
puts(toBeReplaced);
puts("\n");
puts("input[]:\n");
puts(input);
printf("Slashcounter = %d\n",slashcounter);
return 0;
Unfortunately, what happens is: that the first word i.e. the word before the first slash is stored correctly but the other two are empty.
What have I done wrong here
the current output with the input this/test/fails
Enter a line of text:
this/test/fails
The arrays have the following content
replace[]:
this
toBeReplaced[]:
input[]:
Slashcounter = 2
Program ended with exit code: 0
p.s. I would also like to ensure that the /
s are not in the output array.
Thank you for your help.