从特定索引字符中删除字符

本文关键字:字符 删除 索引 | 更新日期: 2024-10-20 17:47:18

我想知道如何从特定索引中删除字符串中的字符,如:

string str = "this/is/an/example"

我想从第三个"/"中删除所有字符,包括这样的字符:

str = "this/is/an"

我尝试了使用子字符串和正则表达式,但找不到解决方案。

从特定索引字符中删除字符

使用字符串操作:

str = str.Substring(0, str.IndexOf('/', str.IndexOf('/', str.IndexOf('/') + 1) + 1));

使用正则表达式:

str = Regex.Replace(str, @"^(([^/]*/){2}[^/]*)/.*$", "$1");

要获得"this/is/an":

string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/'));

如果你需要保留斜线:

string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/')+1);

这需要至少有一个斜杠。如果没有,你应该事先检查一下,不要抛出异常:

string str = "this.s.an.example";
string newStr = str;
if (str.Contains('/'))
    newStr = str.Remove(str.LastIndexOf('/'));

如果获得第三个很重要,那么为它创建一个动态方法,如下所示。输入字符串,以及要返回的"文件夹"。在您的示例中,3将返回"this/is/an":

    static string ReturnNdir(string sDir, int n)
    {
        while (sDir.Count(s => s == '/') > n - 1)
            sDir = sDir.Remove(sDir.LastIndexOf('/'));
        return sDir;
    }

这个正则表达式就是答案:^[^/]*'/[^/]*'/[^/]*。它将捕获前三个块。

var regex = new Regex("^[^/]*''/[^/]*''/[^/]*", RegexOptions.Compiled);
var value = regex.Match(str).Value;

我认为最好的方法是创建一个扩展

     string str = "this/is/an/example";
     str = str.RemoveLastWord();
     //specifying a character
     string str2 = "this.is.an.example";
     str2 = str2.RemoveLastWord(".");

使用此静态类:

  public static class StringExtension
 {
   public static string RemoveLastWord(this string value, string separator = "")
   {
     if (string.IsNullOrWhiteSpace(value))
        return string.Empty;
     if (string.IsNullOrWhiteSpace(separator))
        separator = "/";
     var words = value.Split(Char.Parse(separator));
     if (words.Length == 1)
        return value;
     value = string.Join(separator, words.Take(words.Length - 1));
     return value;
  }
}