[英]Is there a better way to determine if a string can be an integer other than try/catch?
[英]Was there a better way to modify this string other than what I did?
我有這樣的字符串:
Sprites \\ /tilesTest.png
我想用/交換\\ /並刪除擴展名,所以看起來像這樣
精靈/平鋪測試
這是我所做的:
string GetImageToLoadPath(string path)
{
path = path.Replace("\\/", "/");
path = path.Substring(0, path.LastIndexOf("."));
return path;
}
有更好的方法嗎? 有沒有辦法使用正則表達式來做到這一點?
我不明白為什么您為此根本不需要正則表達式。 字符串函數對於解決此類問題確實很有幫助,我會做與您已經做過的相同的事情,但可能會讓它變成一個襯里說
string GetImageToLoadPath(string path)
{
return path.Replace("\\/", "/").Substring(0, path.LastIndexOf("."));
}
嘗試下面的代碼,您可以從: Regex.Replace方法(字符串,字符串)獲取更多詳細信息。
string input = @"Sprites\/tilesTest.png";
string pattern = @"(\\)?(.png)?";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
我懷疑正則表達式是否是處理此類文件路徑的合適工具。
對於目錄和文件名, Path.Combine
(以及Path.GetDirectoryName
和Path.GetFileNameWithoutExtension
)可能很方便,尤其是在目錄分隔符未知的情況下。 至於\\/
替換,您的方法似乎是最好的。
Path.Combine(Path.GetDirectoryName(s), Path.GetFileNameWithoutExtension(s))
.Replace(@"\/", "/");
參見C#演示 :
using System;
using System.IO;
public class Test
{
public static void Main()
{
var s = @"Sprites\/tilesTest.png";
Console.Write(GetStr(s));
}
public static string GetStr(string s) {
return Path.Combine(Path.GetDirectoryName(s), Path.GetFileNameWithoutExtension(s)).Replace(@"\/", "/");
}
}
因此, Path.GetDirectoryName
獲取文件夾路徑, Path.GetFileNameWithoutExtension
獲取文件名,但不包括擴展名,而Path.Combine
將路徑名與系統默認目錄分隔符連接起來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.