【问题标题】:C# Getting the text between 2 characters in a stringC#获取字符串中2个字符之间的文本
【发布时间】:2013-12-05 13:17:14
【问题描述】:
public String GetDirectory(String Path)
    {
        Console.WriteLine("Directorul: ");
        var start = Path.IndexOf(":") + 6;
        var match2 = Path.Substring(start, Path.IndexOf(".") - start);
        return Path;      

    }

我需要获取此字符串中两个字符之间的路径字符串: "C:\Documents\Text.txt"

我希望它显示 ':' 和 '.' 之间的文本最后是:“\Documents\Text”

【问题讨论】:

  • 你为什么要给.IndexOf(":")加6?这对我来说是零意义,让我想知道你是否理解该方法的作用。
  • 你为什么要那个?您究竟想从 GetDirectory 返回什么? System.IO.Path 有很多方法可以获取文件的目录、扩展名、删除或更改扩展名等。也许你要找的东西在那里?

标签: c# string path


【解决方案1】:
int start_index = Path.IndexOf(':')+1;
int end_index = Path.LastIndexOf('.');
int length = end_index-start_index;
string directory = Path.Substring(start_index,length);

【讨论】:

  • 你应该从第二个参数中减去开始......(就像其他答案一样)
  • 理论上可行,但我们应该检查没有找到:. 的情况。
【解决方案2】:

Linq 总是令人着迷:

string s = string.Join("",
                       Path.SkipWhile(p => p != ':')
                           .Skip(1)
                           .TakeWhile(p => p != '.') 
                      );

【讨论】:

    【解决方案3】:

    您可以使用字符串操作,但也可以使用 System.IO.Path 函数来获得 - 在我个人看来 - 更优雅的解决方案:

    string path = @"C:\Documents\Text.txt";
    
    string pathRoot = Path.GetPathRoot(path);  // pathRoot will be "C:\", for example
    string result = Path.GetDirectoryName(path).Substring(pathRoot.Length - 1) +
                  Path.DirectorySeparatorChar + 
                  Path.GetFileNameWithoutExtension(path);       
    
    Console.WriteLine(result);
    

    【讨论】:

      【解决方案4】:

      您应该返回 match2 而不是路径,因为路径将保留为 C:\Documents\Text.txt

      public String GetDirectory(String Path)
      {
          Console.WriteLine("Directorul: ");
          var start = Path.IndexOf(":") + 6;
          var match2 = Path.Substring(start, Path.IndexOf(".") - start);
          return match2;      
      
      }
      

      【讨论】:

        【解决方案5】:
        patch = patch.Substring(patch.IndexOf(':') + 1, patch.IndexOf('.') - 2);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-18
          • 1970-01-01
          • 1970-01-01
          • 2013-02-09
          • 1970-01-01
          • 1970-01-01
          • 2022-12-13
          相关资源
          最近更新 更多