[英]Selecting a specific part of a string C#
我正在嘗試創建一個新字符串,它從現有字符串中刪除某些字符,例如
string path = "C:\test.txt"
所以字符串“pathminus”將取出“C:\”,例如
string pathminus = "test.txt"
有很多方法可以刪除字符串的某個部分。 以下是幾種方法:
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
您還可以使用正則表達式來查找和替換字符串的一部分,但這有點困難。 您可以在 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);
}
}
}
這完全取決於您想對字符串做什么,在這種情況下,您可能只想刪除C:\
但下次您可能想對字符串進行其他類型的操作,可能會刪除尾部等,然后以上不同的方法可能會幫助你。
字符串 class 提供了各種方法來做到這一點。
如果您想通過刪除前三個字符將“C:\test.txt”更改為“test.txt”:
path.Substring(3);
如果要從字符串中的任何位置刪除“C:\”:
path.Replace("C:\", "");
或者,如果您特別想要文件名,無論路徑有多長:
Path.GetFileName(path);
根據您的意圖,有很多方法可以做到這一點。 我更喜歡使用 static class Path
。
對於這個特定示例,我將查看路徑Class。 對於您的示例,您可以調用:
string pathminus = Path.GetFileName(path);
你看過Substring方法嗎?
如果字符串實際上是文件路徑,請使用Path.GetFileName
方法獲取其中的文件名部分。
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);
}
對於更一般的字符串,請使用string.Split(inputChar)
,它將一個字符作為參數並將字符串拆分為string[]
,只要找到該 inputChar 。
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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.