.Net中的字符串分离分为两部分 [英] String separation in .Net with two part

查看:75
本文介绍了.Net中的字符串分离分为两部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我在C#中有一个输入字符串,例如

Hi All,
I have a input string in C# like

string Str="L24789A-12345Ax.DAT";



现在我必须像这样分开Str



now I have to separate the Str like

string Str1,Str2
str1="L24789A";
Str2="12345Ax";



不应该来.DAT

任何人都可以帮我吗
多亏了All.



There should not come .DAT

Can any one help me please
Thanks to All.

推荐答案

我将使用正则表达式,因为在这种情况下,您想拆分一件事,然后删除另一件事.的确,Path.GetFilenameWithoutExtension将为您删除.DAT,然后您可以在-上拆分.

好的,我将使用[[^-] *)-([^.] *).DAT作为正则表达式,然后在运行它时,两个捕获的组将是您想要的两个字符串.您可以将DAT替换为更通用的名称,以匹配任何文件名.
I would use regular expressions, as in this case you want to split on one thing, and also remove another. It IS true that Path.GetFilenameWithoutExtension will remove the .DAT for you and you could just split on the - after that.

OK, I would use ([^-]*)-([^.]*).DAT as the regex, and then when you run it, the two captured groups will be the two strings you want. You can replace DAT with something more general to match any filename.


请尝试使用以下代码段.

Try like following code snippet.

string Str = "L24789A-12345Ax.DAT";
string strWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(Str);
string[] splitArray = strWithoutExtension.Split('-');
string firstPart = splitArray[0];
string secondPart = splitArray[1];


它可能会对您有所帮助,因为考虑到性能,该解决方案也是最佳选择:

It may help you because this solution will be the best by considering performance as well:

static void Main(string[] args)
        {
            string a = "L24789A-12345Ax.DAT";
            string[] b = (a.Replace(".DAT", "")).Split(''-'');
            Console.WriteLine("first = " + b[0]);
            Console.WriteLine("second = " + b[1]);
            Console.ReadLine();
        }


这篇关于.Net中的字符串分离分为两部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆