0

I am trying to substring but getting exception throwing.

 my string  "currentUserLogin" is uponet\\xyz

so what I want final result is xyz

string currentUser = currentUserLogin.Substring(currentUserLogin.LastIndexOf("'\'"));
K.Z
  • 5,201
  • 25
  • 104
  • 240

3 Answers3

3

Try:

string currentUser = currentUserLogin.Substring(currentUserLogin.LastIndexOf("\\") + 1);

I should also point out that you will want some actual error handling. This will throw an IndexOutOfRangeException if the \ comes at the very end of the string.

Relevant documentation: https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

MarkPflug
  • 28,292
  • 8
  • 46
  • 54
  • that returns a \xyz wierd, since we ask for the last ? –  Sep 30 '15 at 14:36
  • Cool :) and no, no error just tested, indexes is zero based so and the substring is not, it uses the actual posiotion in the string 1,2,3 etc. so adding the 1 effectively converts it :) ... just had to test it my self –  Sep 30 '15 at 14:48
2

Safer way to do it is to check if it is in the string first, or check if index > -1.

int index = currentUserLogin.LastIndexOf('\\');
if (index > -1)
{
    if (index + 1 == currentUserLogin)
    {
        currentUser = string.Empty;
    }
    else
    {
        currentUser = currentUserLogin.SubString(index + 1);
    }
}
Philippe Paré
  • 4,279
  • 5
  • 36
  • 56
  • This solution is probably more desirable than catching an exception. There is overhead that comes with exception handling. See post on C# try/catch overhead: http://stackoverflow.com/questions/52312/what-is-the-real-overhead-of-try-catch-in-c – iCode Sep 30 '15 at 14:50
  • This will still throw an exception if the \ is at the end of the string. – MarkPflug Sep 30 '15 at 14:52
  • True, I'll add a test for this – Philippe Paré Sep 30 '15 at 15:06
1

This here works like a charm

        string currentUserLogin = "uponet\\xyz"; //Login
        string[] currentUserParts = currentUserLogin.Split('\\');// splits in parts of [uponet],[],[xyz]
        string currentUser = currentUserParts[currentUserParts.Count() - 1]; // get last from array

\ is a escape charector so by it standing a lone the compiler dont know what to do with it, the correct way to use e.g:

  • \r that is a new line
  • \\ that translate to \

and so forth

Hope this helps :)