C# c语言中的字符串操作#

C# c语言中的字符串操作#,c#,.net,string,C#,.net,String,我有一个这样的字符串,它是由一些反斜杠分隔的一些名称: string mainString = @"Sean\John\Rob\fred"; 我希望姓氏是字符串中的姓氏(在所有反斜杠之后),如何以上述字符串格式获取姓氏,在本例中为“fred” 谢谢。你是说: var list = mainString.Split('\\'); return list[list.Length-1]; 您可以使用LINQ解决此问题: string mainString = @"Sean\John\\Rob\fr

我有一个这样的字符串,它是由一些反斜杠分隔的一些名称:

string mainString = @"Sean\John\Rob\fred";
我希望姓氏是字符串中的姓氏(在所有反斜杠之后),如何以上述字符串格式获取姓氏,在本例中为“fred”

谢谢。

你是说:

var list = mainString.Split('\\');
return list[list.Length-1];

您可以使用LINQ解决此问题:

string mainString = @"Sean\John\\Rob\fred";
var fred = mainString
   .Split("\\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
   .Last();

您还可以使用
LastOrDefault()
保护自己免受空字符串或不包含任何
\
的字符串的攻击。然后,
fred
将仅为
null

当您要按字符分割字符串时,只需执行
split()
,这将返回一个包含所有所需名称的数组

string mainString = "Sean\John\\Rob\fred";

string[] breakMe = mainString.Split('\\');

// to get the 'fred' part:
breakMe [breakMe.length-1];

我不明白你的问题是用另一个名字…

首先,在字符串前面加上一个@,这样就不会把@看作转义序列:

 string mainString = @"Sean\John\\Rob\fred";
    var names = mainString.Split('\\');
    lastName = names[names.Length-1];
string mainString = @"Sean\John\Rob\fred";
然后你可以这样得到你的姓:

string lastname = mainString.Substring( mainString.LastIndexOf('\\')+1);
请注意,如果字符串不包含至少一个\,则会出现异常,因此在尝试获取子字符串之前,请进行检查以确认是否包含\

对于长输入,这应该比使用
Split
更快,因为当您知道只需要最后一个值时,不必将字符串拆分为数组。

有几种方法

string[] tokens = mainString.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
string myString = tokens[tokens.Length - 1];
  • 在字符串中向后走。从末尾开始搜索,直到找到一个“\”
  • 使用正则表达式,特别是回溯。检查前面有“\”的单词/数字(如果允许的话)
  • 编辑:
    根据您的输入看起来如何,Øyvind Knobloch Bråthen的答案可能是更好的方法,因为它不搜索和拆分整个字符串,因此速度更快。

    这应该可以做到:

     string[] names = mainString.Split(new char[]{'\\'}, StringSplitOptions.RemoveEmptyEntries);
     string result = names[names.Length - 1];
    
    在这种情况下,使用
    Split
    ——正如大多数其他答案所建议的那样——是过分的,并且没有充分的理由分配一个临时数组。这个怎么样

    string lastString = mainString.Substring(mainString.LastIndexOf('\\') + 1);
    

    这可能会导致在优化实现上不进行任何复制:

            string mainString = @"Sean\John\\Rob\fred";
            var last = mainString.Reverse().TakeWhile(ch => '\\' != ch).Reverse();
    
    很遗憾,OP可能真的需要一个字符串,因为字符串是不可变的,这需要您构造一个新的字符串实例:

            mainString = new string(last.ToArray());
    
    并不是说我会这么做,但人们一直在寻找一种非侵入性的方式,所以。。。给你


    下面是mono 2.8.2 C#4.0(dmcs)编译器在-optimize+模式下发出的IL

    mainString.Substring(mainString.LastIndexOf('\\')+1)
    反对

    mainString.Reverse()
    
    mainString=新字符串(last.ToArray())
    
    .locals init(字符串V_0,类[mscorlib]System.Collections.Generic.IEnumerable`1 V_1)
    IL_0000:ldstr“肖恩\\约翰\\\\罗伯\\弗雷德”
    IL_0005:stloc.0
    IL_0006:ldloc.0
    IL_0007:调用类[mscorlib]System.Collections.Generic.IEnumerable`1类[System.Core]System.Linq.Enumerable::Reverse(类[mscorlib]系统。。。
    IL_000c:ldsfld类[mscorlib]System.Func`2 qqq.MainClass::'f_uam$cache0'
    IL_0011:brtrue.s IL_0024
    IL_0013:ldnull
    IL_0014:ldftn布尔类qqq.main类::'m__0'(字符)
    IL_001a:newobj实例无效类[mscorlib]System.Func`2::'.ctor'(对象,本机int)
    IL_001f:stsfld类[mscorlib]System.Func`2 qqq.main类::'f_am$cache0'
    IL_0024:ldsfld类[mscorlib]System.Func`2 qqq.MainClass::'f_uam$cache0'
    IL_0029:调用类[mscorlib]System.Collections.Generic.IEnumerable`1类[System.Core]System.Linq.Enumerable::TakeWhile(类[mscorlib]系统。。。
    IL_002e:调用类[mscorlib]System.Collections.Generic.IEnumerable`1类[System.Core]System.Linq.Enumerable::Reverse(类[mscorlib]系统。。。
    IL_0033:stloc.1
    IL_0034:ldloc.1
    IL_0035:call!!0[]类[System.Core]系统.Linq.Enumerable::ToArray(类[mscorlib]系统.Collections.Generic.IEnumerable`1)
    IL_003a:newobj实例无效字符串::'.ctor'(字符[])
    IL_003f:stloc.0
    //
    //
    //将Lambda表达式(ch=>'\\'!=ch)编译为:
    // 
    //方法行3
    .method私有静态隐藏
    默认布尔'm__0'(字符通道)cil管理
    {
    .custom instance void class[mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::“.ctor”(=(01 00)/。。。。
    //方法从RVA 0x214c开始
    //代码大小9(0x9)
    .maxstack 8
    IL_0000:ldc.i4.s 0x5c/'\\'字符
    IL_0002:ldarg.0
    IL_0003:ceq
    IL_0005:ldc.i4.0
    IL_0006:ceq
    IL_0008:ret
    }//方法MainClass::m\uu 0的结尾
    

    应该清楚哪种方法更优化:)

    那么最后一个字符串是什么样子的呢?到目前为止你都试过什么了?如果你完全迷路了,可以试一下split-.+1:
    子字符串
    似乎是这里最有效的变量
    split
    @Josh:我也碰巧认为它比大多数其他答案更具可读性。“将子字符串从最后一个\字符以外的一个字符开始”。它完全是自描述的:规范被重新编写为代码。因此,很多问题都归结为如何表述问题。一个名为“break”?;)的字符串数组)哈哈……我今天过得很糟糕:-/这就是要走的路。声明性语言总是简单且可读性很强。@Josh:你真的认为这比使用
    子字符串和
    LastIndexOf
    更具声明性/可读性吗@卢卡:如果我告诉你在一系列以“\\”分隔的名字中给我姓氏,你会怎么做?我会说,“用分隔符把它们分开,给我最后一个。”。“声明式语言就是用简单的人工术语描述一个问题,并让编译器来解决细节问题。如果你的问题不需要原始的性能,没有人会在意。你真的认为.Split().Last()会花那么多时间运行吗?不。Split vs Substring的性能是1
            string mainString = @"Sean\John\\Rob\fred";
            var last = mainString.Reverse().TakeWhile(ch => '\\' != ch).Reverse();
    
            mainString = new string(last.ToArray());
    
        .locals init (string  V_0)
        IL_0000:  ldstr "Sean\\John\\\\Rob\\fred"
        IL_0005:  stloc.0
        IL_0006:  ldloc.0
        IL_0007:  ldloc.0
        IL_0008:  ldc.i4.s 0x5c
        IL_000a:  callvirt instance int32 string::LastIndexOf(char)
        IL_000f:  ldc.i4.1
        IL_0010:  add
        IL_0011:  callvirt instance string string::Substring(int32)
        IL_0016:  stloc.0
    
       .locals init (string  V_0, class [mscorlib]System.Collections.Generic.IEnumerable`1<char>  V_1)
       IL_0000:  ldstr "Sean\\John\\\\Rob\\fred"
       IL_0005:  stloc.0
       IL_0006:  ldloc.0
       IL_0007:  call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0> class [System.Core]System.Linq.Enumerable::Reverse<char> (class [mscorlib]System...
       IL_000c:  ldsfld class [mscorlib]System.Func`2<char,bool> qqq.MainClass::'<>f__am$cache0'
       IL_0011:  brtrue.s IL_0024
    
       IL_0013:  ldnull
       IL_0014:  ldftn bool class qqq.MainClass::'<Main>m__0'(char)
       IL_001a:  newobj instance void class [mscorlib]System.Func`2<char, bool>::'.ctor'(object, native int)
       IL_001f:  stsfld class [mscorlib]System.Func`2<char,bool> qqq.MainClass::'<>f__am$cache0'
       IL_0024:  ldsfld class [mscorlib]System.Func`2<char,bool> qqq.MainClass::'<>f__am$cache0'
       IL_0029:  call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0> class [System.Core]System.Linq.Enumerable::TakeWhile<char> (class [mscorlib]Syst...
       IL_002e:  call class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0> class [System.Core]System.Linq.Enumerable::Reverse<char> (class [mscorlib]System...
       IL_0033:  stloc.1
       IL_0034:  ldloc.1
       IL_0035:  call !!0[] class [System.Core]System.Linq.Enumerable::ToArray<char> (class [mscorlib]System.Collections.Generic.IEnumerable`1<!!0>)
       IL_003a:  newobj instance void string::'.ctor'(char[])
       IL_003f:  stloc.0
    
       //
       //
       // With the Lambda expression (ch => '\\' != ch) compiled to:
       // 
       // method line 3
       .method private static hidebysig
              default bool '<Main>m__0' (char ch)  cil managed
       {
           .custom instance void class [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::'.ctor'() =  (01 00 00 00 ) // ....
    
           // Method begins at RVA 0x214c
           // Code size 9 (0x9)
           .maxstack 8
           IL_0000:  ldc.i4.s 0x5c  // '\\' character
           IL_0002:  ldarg.0
           IL_0003:  ceq
           IL_0005:  ldc.i4.0
           IL_0006:  ceq
           IL_0008:  ret
       } // end of method MainClass::<Main>m__0