Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last part of a string in C

Tags:

c

string

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.

like image 200
Twisterz Avatar asked Nov 02 '22 04:11

Twisterz


2 Answers

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.

like image 117
HelloWorld123456789 Avatar answered Nov 15 '22 06:11

HelloWorld123456789


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;
}
like image 39
Adam Burry Avatar answered Nov 15 '22 05:11

Adam Burry