C# 在字符串中插入字符串

C# 在字符串中插入字符串,c#,string,C#,String,在字符串中插入子字符串时遇到问题 我想要的是将“/thumbs”注入到stringpath中 /media/pictures/image1.jpg 我想将/thumbs/插入路径的最后一部分,如下所示: /media/pictures/thumbs/image1.jpg 是否可以使用linq?试试这个,您可以得到最后一个正斜杠的索引,并在该点插入额外的字符串 不确定为什么会投否决票,但我保证它是有效的 string original = "/media/pictures/image1.jpg

在字符串中插入子字符串时遇到问题 我想要的是将
“/thumbs”
注入到stringpath中

/media/pictures/image1.jpg
我想将/thumbs/插入路径的最后一部分,如下所示:

/media/pictures/thumbs/image1.jpg

是否可以使用linq?

试试这个,您可以得到最后一个正斜杠的索引,并在该点插入额外的字符串

不确定为什么会投否决票,但我保证它是有效的

string original = "/media/pictures/image1.jpg";
string insert = "thumbs/";
string combined = original.Insert(original.LastIndexOf("/") + 1, insert);
我会使用这个类,最好是在您自己的实用程序方法中,或者作为扩展方法

string pathWithThumbs = Path.Combine(Path.Combine(Path.GetDirectoryName(path), "thumbs"), Path.GetFileName(path));
林克似乎不适合这里;您并不是真的在查询集合。另外,
Path
类会自动为您处理大多数斜线和角点情况

编辑:正如@juharr所指出的,从4.0开始,有一个方便的重载使其更加简单:

string pathWithThumbs = Path.Combine(Path.GetDirectoryName(path), "thumbs", Path.GetFileName(path));
EDITx2:Hrrrm,正如@DiskJunky指出的,这种路径用法实际上会将正斜杠替换为反斜杠,因此只需在那里抛出一个
Replace(“\\”,“/”
调用

林克有可能吗

这个过程不需要使用Linq。您可以使用方法

返回一个新字符串,其中指定的字符串在指定位置插入 在此实例中指定的索引位置

产出

/media/pictures/thumbs/image1.jpg

这里有一个

对于类似路径操作的内容,最好使用
System.IO
名称空间,特别是
路径
对象。你可以这样做

string path = "/media/pictures/image1.jpg";
string newPath = Path.Combine(Path.GetDirectoryName(path), "thumbs", Path.GetFileName(path)).Replace(@"\", "/");

我将使用名为
Path
的System.IO类

以下是长(er)版本,仅供演示之用:

string pathToImage = "/media/pictures/image1.jpg";

string dirName = System.IO.Path.GetDirectoryName(pathToImage);
string fileName = System.IO.Path.GetFileName(pathToImage);
string thumbImage = System.IO.Path.Combine(dirName, "thumb", fileName);

Debug.WriteLine("dirName: " + dirName);
Debug.WriteLine("fileName: " + fileName);
Debug.WriteLine("thumbImage: " + thumbImage);
这是一条单行线:

Debug.WriteLine("ShortHand: " + Path.Combine(Path.GetDirectoryName(pathToImage), "thumb", Path.GetFileName(pathToImage)));
我得到以下输出:

dirName: \media\pictures
fileName: image1.jpg
thumbImage: \media\pictures\thumb\image1.jpg

ShortHand: \media\pictures\thumb\image1.jpg

为什么要使用linq而不仅仅是字符串插入方法?为什么要使用link而不仅仅是nice
Path
实用程序类来帮助完成类似的工作<代码>字符串pathWithThumbs=Path.Combine(Path.Combine(Path.GetDirectoryName(Path),“thumbs”)、Path.GetFileName(Path))简单检查最后一个/(或从末尾算起的第一个),然后插入/thumbs
路径。Combine
现在将获取一个param数组,因此不需要嵌套它们。我想这是在.NET4.0中添加的。@juharr谢谢!我已经有很长一段时间没有直接使用
Path
;非常好!解决方案的结果将“/”替换为“\”—您需要在解决方案结束时使用Replace()调用来完成它chain@DiskJunky+1谢谢你的关注。我没有否决投票,但我假设是“你应该使用
Path
方法而不是
string
方法”参数。很可能,但是对于这样一个简单的操作,我觉得有点不合适。
string.Insert
的存在是有原因的;)是的,我不确定Path方法是否能使斜杠保持正确的方向/vs\n使用
Path.combined
只是在以后替换斜杠似乎很愚蠢<代码>字符串。插入也更容易阅读,实际上不需要过度编码。@AdamKDean,这不是生产代码。Path对象的版本性稍高一些,类似这样的内容可能会放入公共库中。也许有点牵强,但这是一项值得做的工作…:-)也就是说,我确实喜欢你的方法——干净利落,切中要害!这将提供/media/pictures/thumbs//image1.jpg,您需要删除其中一个斜杠。
dirName: \media\pictures
fileName: image1.jpg
thumbImage: \media\pictures\thumb\image1.jpg

ShortHand: \media\pictures\thumb\image1.jpg