代码之家  ›  专栏  ›  技术社区  ›  JimDel

当有多个字符时,如何使用indexof来选择特定字符?

  •  0
  • JimDel  · 技术社区  · 16 年前

    当有多个子字符串时,如何使用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);
    }}
    
    4 回复  |  直到 16 年前
        1
  •  7
  •   Jon Skeet    16 年前

    更好的方法是 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) 只是给你一个临时目录,因为它不知道路径已经是一个目录了。)

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

        2
  •  2
  •   Reed Copsey    16 年前

    为什么不直接使用系统类来处理呢?

    string folder = Environment.GetFolder(Environment.SpecialFolder.LocalApplicationData);
    
        3
  •  1
  •   Jay    16 年前

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

    在我自学编程生涯的头几年里,我做了最复杂的字符串操作,在我意识到其他人已经解决了所有这些问题之前,我拿起了 Mastering Regular Expressions . 我强烈推荐。

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

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

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

        4
  •  0
  •   Austin Salonen gmlacrosse    16 年前

    我会使用directoryinfo类。

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