如何仅选择长字符串中重复符号后的字符

时间:2011-12-20 19:01:54

标签: c# c#-3.0

如果我正在使用C#,我有一个来自数据库的字符串:

\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML

我只想要这部分字符串:

1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML

如果有多个“\”符号,我怎么能得到这个字符串?

7 个答案:

答案 0 :(得分:3)

使用String.Split按部分拆分字符串,然后获取最后部分。

使用LINQ Enumerable.Last()

text.Split('\\').Last();

// todo: add null-empty checks, etcs
var parts = text.Split('\\');
strign lastPart = parts[parts.Length - 1];

答案 1 :(得分:3)

您可以使用LastIndexOf()类的String方法:

 string s = @"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";

 Console.Out.WriteLine(s.Substring(s.LastIndexOf('\\') + 1));

希望,这有帮助。

答案 2 :(得分:2)

您可以使用String.LastIndexOf(“\”)和String.Substring(lastIndex + 1)的组合。您也可以使用(仅在您提供的示例中)Path.GetFileName(theString)。

答案 3 :(得分:2)

string [] x = line.Split('\');

string goal = x [x.Length-1];

但是linq会更容易

答案 4 :(得分:1)

您可以使用正则表达式或用“\”符号拆分字符串并获取数组的最后一个元素

using System.Linq;

public class Class1
{
    public Class1()
    {
        string s =
            @"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML";

        var array = s.Split('\\');

        string value = array.Last();
    }
}

答案 5 :(得分:1)

newstring = string.Substring(string.LastIndexOf(@"\")+1);

答案 6 :(得分:0)

看起来原始字符串就像filePath一样。 这可能是一个简单的解决方案。

string file = @"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
            string name = System.IO.Path.GetFileName(file);