Character Right in C #

How do I get the right (string) in C #? if user = "MyDomain \ jKing" I just want to click on the specified line.

      int index;
      string user;

    index = User.Identity.Name.IndexOf("\\");
    user = (index > 0 ? User.Identity.Name.Substring(0, index) : "");
+3
source share
4 answers
string user = User.Identity.Name
user= user.Remove(0, user.IndexOf(@"\")+ 1);
+6
source
var user = User.Identity.Name;
var index = user.IndexOf("\\");
if (index < 0 || index == user.Length - 1) 
{
    user = string.Empty;
}
else 
{
    user = user.Substring(index + 1);
}
+4
source
User.Identity.Name.Split(@"\")[1]
+3
source

You can also make it reusable. Below are some extension methods created after the XLST functions substring-beforeand substring-afterto make it general.

Using: var userNm = (User.Identity.Name.Contains(@"\") ? User.Identity.Name.SubstringAfter(@"\") : User.Identity.Name);

public static class StringExt {
   public static string SubstringAfter(this string s, string searchString) {
      if (String.IsNullOrEmpty(searchString)) return s;
      var idx = s.IndexOf(searchString);
      return (idx < 0 ? "" : s.Substring(idx + searchString.Length));
   }

   public static string SubstringBefore(this string s, string searchString) {
      if (String.IsNullOrEmpty(searchString)) return s;
      var idx = s.IndexOf(searchString);
      return (idx < 0 ? "" : s.Substring(0, idx));
   }
}
+1
source

Source: https://habr.com/ru/post/1753575/


All Articles