I needed the ability to truncate the trailing end of path strings in a routine that builds new search paths as it recursively searches directories. After not finding what I was looking for I created function below.
Expected behavior is that function remove_trailing_chars()
will update in
to remove any occurrences of chars contained in rem
, iff they exist contiguously at the very end of the original version of in
.
Once a character in the in
string becomes the trailing char and it is not included in rem
, then function updates in
with latest version and returns.
it has been tested for several variations of input char
arrays in
and rem
, including these.
char in[] = "this is a string with \\ *\\*";//edit this string as needed to test
char rem[] = "\\* ";//edit this string as needed to test
results in "this is a string with"
without following space
char in[] = "this is a string with *\\*";//edit this string as needed to test
char rem[] = "\\*";//edit this string as needed to test
results in "this is a string with "
includes following space
I am interested in suggestions for efficiency improvements in speed, and readability improvements. (suggestions on more idiomatic methods are welcome.) I do not believe memory should be an issue with this for my usage, but if there are thoughts on any pitfalls in that area, please include them as well.
Here is the code, including one usage case... (Compiler command line and its disassembly are included further down as well.)
#include <stdbool.h>//bool
#include <string.h>//strlen, strcpy
#include <stdlib.h>
//prototypes
void remove_trailing_chars(char *in, const char *rem);
/// demonstrate removing all chars in 'rem' if trailing in 'in'.
int main(void)
{
char in[] = "this is a string with \\ *\\*";//edit this string as needed to test
char rem[] = "\\* ";//edit this string as needed to test
remove_trailing_chars(in, rem);
return 0;
}
/// remove all occurrences of chars in 'rem' from end of 'in'
void remove_trailing_chars(char *in, const char *rem)
{
bool found = true;//when false, last char of 'in' found no matches in 'rem'
int len = strlen(in);
char in_dup[len+1];
strcpy(in_dup, in);
while(found)
{
found = false;//for this element of rem
len = strlen(in_dup);
int i = 0;
while(rem[i])
{
if(in_dup[len-1] == rem[i])
{
in_dup[len - 1] = 0;
found = true;
break;
}
else
{
i++;
}
}
}
strcpy(in, in_dup);
}
Using GCC, build was done with:
Release target:
mingw32-gcc.exe -Wall -O2 -Wall -std=c99 -g -c C:\tempExtract\remove_trainling_chars\main.c -o obj\Release\main.o
Debug target: (to allow viewing disassembly)
gcc.exe -Wall -g -Wall -std=c99 -g -c C:\tempExtract\remove_trainling_chars\main.c -o obj\Debug\main.o