24

What I have is a giant text file that contains a bunch of strings that are split by \. The problem for me is there can be 5 \ or 4 \ or 3 \.

What I need to to pull the last \ no matter how many of them there are. Any help is appreciated.

Examples:

I\need\this
I\want\line\this
Hello\give\me\all\this

I need the word this for example, but obviously it's not just the word this.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • Given a string without a "\", should the function return the entire string or an empty string? e.g. Pass it "Hello", should it return "Hello", or ""? – Binary Worrier Jul 15 '10 at 13:35

3 Answers3

54
string last = inputString.Substring(inputString.LastIndexOf('\\') + 1);
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • +1: With the caveat that you check for an empty string first `if(!string.IsNullOrEmpty(inputString))`, and that if there is no "\" in the string, then you want the entire string :) – Binary Worrier Jul 15 '10 at 13:04
  • 11
    Null checking is correct, should always check that. The good thing about LastIndexOf(..) + 1, is that the LastIndexOf(..) will return -1 for a character which could not be found, so the net result is the Substring is taken from position 0, which is the start of the string, so the whole string is returned. – Matthew Abbott Jul 15 '10 at 13:06
  • 1
    Agreed, on all points, but the requirement may well be that if there is no "\" that an empty string be returned. I'm just saying that one should check which is the required behaviour. – Binary Worrier Jul 15 '10 at 13:26
19
string myString = inputString.Split('\\').Last();
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
6

Almost forgot this one (although it's a bit cheeky):

string result = Path.GetFilename(input);

Flynn1179
  • 11,925
  • 6
  • 38
  • 74
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – lxg Oct 17 '14 at 08:09
  • 1
    It has been flagged because of low quality. And it is indeed, it works only on Windows. (I realize that the question is about C#, which is usually used in Windows environments, but it can be ported to other platforms through Mono.) – lxg Oct 17 '14 at 08:38
  • 3
    I'll accept that the fact it only works on windows is probably relevant, but that's not really a justifiable argument for claiming it's low quality. MOST answers will not work in some circumstances. In fact, the OP didn't explain WHY he wants to do this, it was entirely possible that extracting a filename was exactly what he wanted to do, certainly it could be ideal for another reader who's looking for an answer for this reason. – Flynn1179 Oct 18 '14 at 09:04