【问题标题】:How to get a count of characters until certain character C#如何获取字符数直到某个字符C#
【发布时间】:2018-01-26 01:50:06
【问题描述】:

我正在尝试获取字符串的完整路径,如下所示:

ksh /u01/Utilities/SSL_Certificates/TestCert_20170724.sh

但我遇到了一个问题,我得到了

/u01/Utilities/SSL_Certificates/Tes

这是因为从 ksh 获取 4 个字符

如何获取从 0 到 "/" 的第一个索引的计数

我拥有的是这样的:

string SSL_configuration_Path = ShellCommand.Substring(ShellCommand.IndexOf("/"), ShellCommand.LastIndexOf("/"));

【问题讨论】:

  • 这就是为什么首先检查documentation 通常会有所帮助。

标签: c# count substring string-length


【解决方案1】:

第二个参数是多少个字符。

不是最后一个字符。

string SSL_configuration_Path = ShellCommand.Substring(
  ShellCommand.IndexOf("/"),
  ShellCommand.LastIndexOf("/") - ShellCommand.IndexOf("/"));

并不是说这是一个好的解决方案,但它应该解释你做错了什么以及为什么它不起作用。

【讨论】:

  • 现在我收到了/u01/Utilities/SSL_Certificates/TestCer
  • 第二个参数是长度?那么你不应该有一个减号而不是加号吗?并转换条款?像这样:ShellCommand.LastIndexOf("/") - ShellCommand.IndexOf("/")
  • 你是对的,我只是减去它,它起作用了!谢谢!
【解决方案2】:

尝试使用专为处理目录和文件名称而设计的Parh 类:

string ShellCommand = "ksh /u01/Utilities/SSL_Certificates/TestCert_20170724.sh";

string path = Path.GetDirectoryName(ShellCommand
  .Substring(line.IndexOfAny(new char[] { 
     Path.AltDirectorySeparatorChar, 
     Path.DirectorySeparatorChar })));

Console.WriteLine(path);

结果:

\u01\Utilities\SSL_Certificates

请注意,您可以使用/\ 作为目录分隔符并获得归一化的最终结果(即使用Path.DirectorySeparatorChar 分隔符)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 2013-02-07
    相关资源
    最近更新 更多