I have a string in C that contains a file path like "home/usr/wow/muchprogram".
I was wondering in C how I can get the string after the last "/". So Then I could store it as a variable. That variable would equal "muchprogram" to be clear.
I am also wondering how I could get everything before that final "/" as well. Thanks in advance.
Start scanning the string from the end. Once you get a /
stop. Note the index
and copy from index+1
to last_index
, to a new array.
You get everything before the final /
as well. You have the index
. Start copying from start_index
to index-1
, to a new array.
Someone else already suggested this, but they forgot to include the C. This assumes it is ok to mutate the source string. Tested with GCC 4.7.3.
#include <stdio.h>
#include <string.h>
int main() {
char* s = "home/usr/wow/muchprogram";
int n = strlen(s);
char* suffix = s + n;
printf("%s\n%s\n", s, suffix);
while (0 < n && s[--n] != '/');
if (s[n] == '/') {
suffix = s + n + 1;
s[n] = '\0';
}
printf("%s\n%s\n", s, suffix);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With