-1

如何删除字符串中的某些字符..

string s="testpage\information.xml"

我只需要 information.xml 怎么做?

4

10 回答 10

1

假设将在其中的值s始终是文件路径,使用Path类来提取文件名

var filename = Path.GetFileName(s);
于 2012-11-07T05:15:49.610 回答
1

System.IO.Path由于字符串包含文件路径信息,因此可能会对您有所帮助。在您的情况下,您可以使用Path.GetFileName(string path)从字符串中获取文件名。

例子

string s = @"testpage\information.xml";
string filename = Path.GetFileName(s);
//MessageBox.Show(filename);

谢谢,
我希望你觉得这有帮助:)

于 2012-11-07T05:17:30.967 回答
0

文件路径的格式为

aaaa\bbb\ccc\dddd\information.xml

要检索最后一个字符串,您可以使用分隔符分割您的字符串\

String path = @"aaaa\bbb\ccc\dddd\information.xml";
String a[] = path.Split('\\');

这将使字符串数组为["aaaa", "bbb", "ccc", "dddd", "information.xml"]

您可以将文件名检索为

String filename = a[a.Length-1];
于 2012-11-07T05:18:02.777 回答
0

如果您使用文件路径,请参阅Path.GetFileName方法 它不会检查文件是否存在。所以会更快。

s = Path.GetFileName(s);

如果需要检查文件是否存在,请使用 File.Exists 类。

另一种方法是使用 String.Split() 方法

string[] arr = s.Split('\\');
if(arr.Length > 0)
{
  s = arr[arr.Length - 1];
}

另一种方法是使用正则表达式

s = Regex.Match(s, @"[^\\]*$").Value;
于 2012-11-07T05:19:09.433 回答
0

如果它是文件路径,那么您可以使用System.IO.Path类 ( MSDN ) 来提取文件名。

string s = "testpage\information.xml"
var filename = Path.GetFilename(s);
于 2012-11-07T05:19:11.897 回答
0

如果它总是在反斜杠分隔符的右边,那么你可以使用:

if (s.Contains(@"\")) 
     s= s.Substring(s.IndexOf(@"\") + 1);
于 2012-11-07T05:21:15.590 回答
0

希望这是你想要的:

var result=s.Substring(s.LastIndexOf(@"\") + 1);
于 2012-11-07T05:27:49.793 回答
0

您可以使用以下代码行来获取文件扩展名。

string filePath = @"D:\Test\information.xml";
string extention = Path.GetExtension(filePath);

如果您需要单独使用文件名,

string filePath  = @"D:\Test\information.xml";
string filename = Path.GetFilename(filePath );
于 2012-11-07T06:16:19.807 回答
0

使用 string.Replcae

string s = @"testpage\information.xml";
s = s.Replace(@"testpage\\",""); // replace  'testpage\' with empty string

你会得到 Output => s=information.xml

@ 只需要因为你的字符串中有反斜杠

有关字符串替换的进一步阅读

http://www.dotnetperls.com/replace

http://msdn.microsoft.com/en-us/library/system.string.replace.aspx

于 2012-11-07T06:30:45.143 回答
-1

在 C++ 中,你可以做这样的事情。基本上从路径的右到左搜索“/”或“\”,并从第一次出现的分隔符开始裁剪字符串:

string ExtractFileName(const string& strPathFileName)
{
    size_t npos;
    string strOutput = strPathFileName;
    if(strPathFileName.rfind(L'/', npos) || strPathFileName.rfind(L'\\', npos))
    {
        strOutput = strPathFileName.substr(npos+1);
    }
    return strOutput;
}
于 2012-11-07T05:22:54.940 回答