选择字符串C#的特定部分

Ada*_*nes 2 .net c# windows

我正在尝试创建一个新字符串,从现有字符串中删除某些字符,例如

string path = "C:\test.txt"
Run Code Online (Sandbox Code Playgroud)

所以字符串"pathminus"将取出"C:\",例如

string pathminus = "test.txt"
Run Code Online (Sandbox Code Playgroud)

Cha*_*ndu 12

使用 Path.GetFileName

例如:

string pathminus = Path.GetFileName(path);
Run Code Online (Sandbox Code Playgroud)


Fil*_*erg 11

有很多方法可以删除字符串的某个部分.这有几种方法可以做到:

var path = @"C:\test.txt";
var root = @"C:\";
Run Code Online (Sandbox Code Playgroud)

运用 string.Remove()

var pathWithoutRoot = path.Remove(0, root.Length);
Console.WriteLine(pathWithoutRoot);                // prints test.txt
Run Code Online (Sandbox Code Playgroud)

运用 string.Replace()

pathWithoutRoot = path.Replace(root, "");
Console.WriteLine(pathWithoutRoot);                // prints test.txt
Run Code Online (Sandbox Code Playgroud)

运用 string.Substring()

pathWithoutRoot = path.Substring(root.Length);
Console.WriteLine(pathWithoutRoot);                // prints test.txt
Run Code Online (Sandbox Code Playgroud)

运用 Path.GetFileName()

pathWithoutRoot = Path.GetFileName(path);
Console.WriteLine(pathWithoutRoot);                // prints test.txt
Run Code Online (Sandbox Code Playgroud)

您也可以使用正则表达式来查找和替换字符串的某些部分,但这有点困难.您可以在MSDN上阅读有关如何在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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这一切都取决于你想对字符串做什么,在这种情况下你可能想要删除,C:\但下次你可能想要用字符串做其他类型的操作,也许删除尾部等,然后上面的不同方法可能会帮助你.