I want to transform a given input in my c program, for example:
foo_bar_something-like_this
into this:
thissomethingbarfoolike
Explanation:
Every time I get a _
, the following text up to, but not including, the next _
or -
(or the end of the line) needs to go to the beginning (and the preceding _
needs to be removed). Every time I get a -
, the following text up to, but not including, the next _
or -
(or the end of the line) needs to be appended to the end (with the -
removed).
If possible, I would like to use regular expressions in order to achieve this. If there is a way to do this directly from stdin, it would be optimal.
Note that it is not necessary to do it in a single regular expression. I can do some kind of loop to do this. In this case I believe I would have to capture the data in a variable first and then do my algorithm.
I have to do this operation for every line in my input, each of which ends with \n
.
EDIT: I had already written a code for this without using anything related to regex, besides I should have posted it in the first place, my apologies. I know scanf should not be used to prevent buffer overflow, but the strings are already validated before being used in the program. The code is the following:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LENGTH 100001 //A fixed maximum amount of characters per line
int main(){
char c=0;
/*
*home: 1 (append to the start), 0 (append to the end)
*str: array of words appended to the begining
*strlen: length of str
*line: string of words appended to the end
*linelen: length of line
*word: word between a combination of symbols - and _
*wordlen: length of the actual word
*/
int home,strlen,linelen,wordlen;
char **str,*line,*word;
str=(char**)malloc(MAX_LENGTH*sizeof(char*));
while(c!=EOF && scanf("%c",&c)!=EOF){
line=(char*)malloc(MAX_LENGTH);
word=(char*)malloc(MAX_LENGTH);
line[0]=word[0]='\0';
home=strlen=linelen=wordlen=0;
while(c!='\n'){
if(c=='-'){ //put word in str and restart word to '\0'
home=1;
str[strlen++]=word;
word=(char*)malloc(MAX_LENGTH);
wordlen=0;
word[0]='\0';
}else if(c=='_'){ //put word in str and restart word to '\0'
home=0;
str[strlen++]=word;
word=(char*)malloc(MAX_LENGTH);
wordlen=0;
word[0]='\0';
}else if(home){ //append the c to word
word[wordlen++]=c;
word[wordlen]='\0';
}else{ //append c to line
line[linelen++]=c;
line[linelen]='\0';
}
scanf("%c",&c); //scan the next character
}
printf("%s",word); //print the last word
free(word);
while(strlen--){ //print each word stored in the array
printf("%s",str[strlen]);
free(str[strlen]);
}
printf("%s\n",line); //print the text appended to the end
free(line);
}
return 0;
}