繁体   English   中英

C#从字符串中拆分和检索值

[英]c# splitting and retrieving values from a string

我有一个像这样的字符串:

"http://localhost:55164/Images/photos/2/2.jpg"

我需要检索文件名和/2/中的/2/ ,并将它们放入自己的字符串中。 由于文件名长度是可变的,我一直在弄乱StringBuilder并进行替换和替换都无济于事。 有人有快速的方法吗?

谢谢

string link = "http://localhost:55164/Images/photos/2/2.jpg"; // your link
string[] x = link.Split('/'); // split it into pieces at the slash
string filename = (x.Length >= 1) ? x[x.Length - 1] : null; // get the last part
string dir = (x.Length >= 2) ? x[x.Length - 2] : null; // get the 2nd last part

编辑 ,检查数组的长度,然后再尝试访问其片段,如下面的注释中所建议的。

您可以作弊并使用Path类。 这更容易,同时又增加了可读性。

string path = "http://localhost:55164/Images/photos/2/2.jpg";
Console.WriteLine(Path.GetFileName(path));
string[] dirSplit = Path.GetDirectoryName(path).Split('\\');
Console.WriteLine(dirSplit[dirSplit.Length - 1]);

我建议使用Path类:

string filename = Path.GetFileName(s);
string dir = Path.GetDirectoryName(s).GetFileName(s);

使用以'/'作为分隔符的Split函数并获取数组的最后2个元素。

            string s = "";
            string[] arr = s.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            string ans = "";
            if (arr.Length > 1)
                ans = arr[arr.Length - 1] + arr[arr.Length - 2];

一种快速的方法是用正斜杠分割字符串。

这样,您将知道数组中的最后一项和倒数第二项将是您所需要的。

这样:

string url = "http://localhost:55164/Images/photos/2/2.jpg";
string[] urlParts = url.Split('/');
string file = urlParts[urlParts.length -1];

我建议您使用为此目的而量身定制的System.Uri类(提供对URI部分的轻松访问),例如,

Uri uri = new Uri("http://localhost:55164/Images/photos/2/2.jpg");
string[] segments = uri.Segments;
foreach (string segment in segments)
{
    Console.WriteLine(segment.Trim('/'));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM