在单词后面的字符串之间添加一个单词
本文关键字:单词 一个 添加 之间 字符串 | 更新日期: 2023-09-27 18:34:04
我想在单词"Photo/"之后的字符串之间添加一个单词,例如:
string path ="C:/Users/tsgill/Desktop/myApp/Photo/11686_Snap1.png"
插入单词"thumb/",例如:
string path ="C:/Users/tsgill/Desktop/myApp/Photo/thumb/11686_Snap1.png"
我尝试拆分它,但无法正确连接所有内容。 让我知道我怎样才能轻松地做到这一点,
你应该使用 Path
类:
string path = "C:/Users/tsgill/Desktop/myApp/Photo/11686_Snap1.png";
path = Path.Combine(Path.GetDirectoryName(path), "thumb", Path.GetFileName(path));
如果你确切地知道你需要把它放在哪里,你可以做一个替换:
string path = path.Replace("Photo", "Photo/thumb");
如果你想在最后一个"/"之后添加
string path = "C:/Users/tsgill/Desktop/myApp/Photo/11686_Snap1.png";
path=path.Insert(path.LastIndexOf('/')+1, "Thumb/");
除了所有其他答案(Tim Schmelter 的答案似乎是最干净的恕我直言,但这取决于您的需要),我只想补充一点,如果您需要对组成目录的每个文件夹进行更多控制,您可以使用以下内容拆分和管理它们:
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
然后重建它,在正确的位置添加缺少的子目录部分。
注意:如前所述,这不是一个完整的答案,而是对其他答案的补充。
以下是动态执行此操作的方法:
public string modify(string yourPath,string yourInsertedWord, string yourWordToChange)
{
int index = yourPath.LastIndexOf(yourWordToChange)
string stringresult = yourPath.insert(index,yourInsertedWord);
return stringresult;
}