【问题标题】:How can I use IndexOf to pick a specific Character when there are more than one of them?当有多个字符时,如何使用 IndexOf 来选择特定字符?
【发布时间】:2011-02-07 14:48:47
【问题描述】:

当有多个字符时,如何使用带有 SubString 的 IndexOf 来选择特定字符?这是我的问题。我想采用路径“C:\Users\Jim\AppData\Local\Temp\”并删除“Temp\”部分。只留下“C:\Users\Jim\AppData\Local\”我已经用下面的代码解决了我的问题,但这假设“Temp”文件夹实际上被称为“Temp”。有没有更好的办法?谢谢

if (Path.GetTempPath() != null) // Is it there?{
tempDir = Path.GetTempPath(); //Make a string out of it.
int iLastPos = tempDir.LastIndexOf(@"\");
if (Directory.Exists(tempDir) && iLastPos > tempDir.IndexOf(@"\"))
{
    // Take the position of the last "/" and subtract 4.
    // 4 is the lenghth of the word "temp".
    tempDir = tempDir.Substring(0, iLastPos - 4);
}}

【问题讨论】:

  • 澄清一下,你想剪掉路径中的最后一个子目录,不管它是否是临时目录?
  • 是的,它将是 TEMP 或可能是 TMP

标签: c# string substring indexof


【解决方案1】:

更好的方法是使用Directory.GetParent()DirectoryInfo.Parent

using System;
using System.IO;

class Test
{
    static void Main()
    {
        string path = @"C:\Users\Jim\AppData\Local\Temp\";
        DirectoryInfo dir = new DirectoryInfo(path);
        DirectoryInfo parent = dir.Parent;
        Console.WriteLine(parent.FullName);
    }    
}

(请注意,Directory.GetParent(path) 只是为您提供了 Temp 目录,因为它不理解该路径已经是一个目录。)

如果你真的想使用LastIndexOf,请使用the overload which allows you to specify the start location

【讨论】:

  • @CAbbott:我快到了 :)
  • @Neal:我知道链接,我只是在敦促 Skeet 先生在他的帖子中加入一个。
  • 不,根本不需要使用 LastIndexOf。它在我脑海中的小工具列表中很容易找到。我不知道GetParent。这对我来说非常有效,而且更加优雅。非常感谢!
  • @CAbbott:下次,您可以随意添加链接。我保证不咬人:)
【解决方案2】:

为什么不直接使用 System 类来处理这个问题?

string folder = Environment.GetFolder(Environment.SpecialFolder.LocalApplicationData);

【讨论】:

    【解决方案3】:

    其他回答者已经展示了实现目标的最佳方式。为了进一步扩展您的知识,我建议您在一般情况下查看正则表达式以满足您的字符串匹配和替换需求。

    在我自学编程生涯的最初几年里,我做了可以想象的最复杂的字符串操作,然后我意识到其他人已经解决了所有这些问题,我拿起了一份Mastering Regular Expressions。我强烈推荐它。

    剥离最后一个目录的一种方法是使用以下正则表达式:

    tempDir = Regex.Match(tempDir, @".*(?=\\[^\\]+)\\?").Value;
    

    它可能看起来很神秘,但这实际上会从路径中删除最后一项,不管它的名称是什么,也不管最后是否有另一个\

    【讨论】:

    • 谢谢杰。我得去看看那本书。我一直想研究正则表达式。
    【解决方案4】:

    我会使用 DirectoryInfo 类。

    DirectoryInfo tempDirectory = new DirectoryInfo(Path.GetTempPath());            
    DirectoryInfo tempDirectoryParent = tempDirectory.Parent;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多