简体   繁体   English

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

[英]Remove characters from a specific index character

I would like to know how can i remove characters in a string from a specific index like : 我想知道如何从特定的索引中删除字符串中的字符:

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

I want to remove all characters from the third '/' including so it would be like this: 我想从第三个“ /”中删除所有字符,包括这样:

str = "this/is/an"

I tried with substring and regex but i cant find a solution. 我尝试使用substring和regex,但找不到解决方案。

Using string operations: 使用字符串操作:

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

Using regex: 使用正则表达式:

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

This regex is the answer: ^[^/]*\\/[^/]*\\/[^/]* . 这个正则表达式就是答案: ^[^/]*\\/[^/]*\\/[^/]* It will capture the first three chunks. 它将捕获前三个块。

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

To get "this/is/an": 要获取“ this / is / an”:

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

If you need to keep the slash: 如果需要保留斜线:

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

This expects there to be at least one slash. 期望至少有一个斜杠。 If none are present, you should check it beforehand to not throw an exception: 如果不存在,则应事先进行检查以免引发异常:

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

If its importaint to get the third one, make a dynamic method for it, like this. 如果它的重要性获得了第三个,则为此创建一个动态方法。 Input the string, and which "folder" you want returned. 输入字符串,以及要返回的“文件夹”。 3 in your example will return "this/is/an": 您的示例中的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;
    }

I think the best way of doing that it's creating a extension 我认为最好的方法就是创建扩展

     string str = "this/is/an/example";
     str = str.RemoveLastWord();

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

With this static class: 使用此静态类:

  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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM