我想创建一个新的字符串,从现有的字符串中删除某些字符,例如选择一个字符串的特定部分C#
string path = "C:\test.txt"
所以字符串“pathminus”将取出“C:\”例如
string pathminus = "test.txt"
我想创建一个新的字符串,从现有的字符串中删除某些字符,例如选择一个字符串的特定部分C#
string path = "C:\test.txt"
所以字符串“pathminus”将取出“C:\”例如
string pathminus = "test.txt"
string类提供了各种各样的方式来做到这一点。
如果你想改变“C:\ test.txt”的“的test.txt”通过去除前三个字符:如果你想删除
path.Substring(3);
:从任何地方“C:\”字符串:
path.Replace("C:\", "");
或者,如果你特别想要的文件名,不管路径是多久呢:
Path.GetFileName(path);
根据根据你的意图,有很多方法可以做到这一点。我更喜欢使用静态类Path
。
你看过Substring方法吗?
如果字符串实际上是一个文件路径,使用Path.GetFileName
方法来获得它的文件名部分。
对于这个特定的例子,我会看看Path类。对于你的榜样,你可以叫:
string pathminus = Path.GetFileName(path);
path.SubString(path.IndexOf('\'))
你想要System.Text.RegularExpressions.Regex
但你到底在做什么?
最简单的形式:
[TestMethod]
public void RemoveDriveFromPath()
{
string path = @"C:\test.txt";
Assert.AreEqual("test.txt", System.Text.RegularExpressions.Regex.Replace(path, @"^[A-Z]\:\\", string.Empty));
}
你只是想获得不带路径的文件的文件名?
如果这样做,而不是:
[TestMethod]
public void GetJustFileName()
{
string path = @"C:\test.txt";
var fileInfo = new FileInfo(path);
Assert.AreEqual("test.txt", fileInfo.Name);
}
有这么多的方法,你可以删除一个字符串的某一部分。这是一对夫妇的方式做到这一点:
var path = @"C:\test.txt";
var root = @"C:\";
使用string.Remove()
var pathWithoutRoot = path.Remove(0, root.Length);
Console.WriteLine(pathWithoutRoot); // prints test.txt
使用string.Replace()
pathWithoutRoot = path.Replace(root, "");
Console.WriteLine(pathWithoutRoot); // prints test.txt
使用string.Substring()
pathWithoutRoot = path.Substring(root.Length);
Console.WriteLine(pathWithoutRoot); // prints test.txt
使用Path.GetFileName()
pathWithoutRoot = Path.GetFileName(path);
Console.WriteLine(pathWithoutRoot); // prints test.txt
您还可以使用正则表达式查找和替换字符串的一部分,这是一个有点困难,但。 You can read on MSDN on how to use Regular Expressions in C#.
下面是关于如何使用string.Remove()
,string.Replace()
,string.Substring()
,Path.GetFileName()
和Regex.Replace()
一个完整的示例:
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
var path = @"C:\test.txt";
var root = @"C:\";
var pathWithoutRoot = path.Remove(0, root.Length);
Console.WriteLine(pathWithoutRoot);
pathWithoutRoot = Path.GetFileName(path);
Console.WriteLine(pathWithoutRoot);
pathWithoutRoot = path.Replace(root, "");
Console.WriteLine(pathWithoutRoot);
pathWithoutRoot = path.Substring(root.Length);
Console.WriteLine(pathWithoutRoot);
var pattern = "C:\\\\";
var regex = new Regex(pattern);
pathWithoutRoot = regex.Replace(path, "");
Console.WriteLine(pathWithoutRoot);
}
}
}
这一切都取决于你想用字符串做什么,在这种情况下,你可能想删除只是C:\
,但下次你可能想用字符串做其他类型的操作,也许删除尾部或类似的,然后上述不同的方法可能会帮助你。
对于更一般的字符串,请使用string.Split(inputChar)
,它将字符作为参数,并在找到inputChar的任何位置将字符串拆分为string[]
。
string[] stringArr = path.Split('\\'); // need double \ because \ is an escape character
// you can now concatenate any part of the string array to get what you want.
// in this case, it's just the last piece
string pathminus = stringArr[stringArr.Length-1];
有趣的,现在看看!谢谢 –