删除子字符串后如何获取剩余的字符串

时间:2012-01-03 13:09:04

标签: c# .net regex

假设我有以下字符串

string temp = "some string contains text which contains demo";

string result = RemainingString(temp,12,8)// string , startIndex ,length

我想要的结果字符串应该是这样的 “包含demo”// contains的一些字符串文本仅从第一位删除。

更新:我想仅使用正则表达式实现此目的。

5 个答案:

答案 0 :(得分:5)

尝试String.Remove方法,它完全符合您的要求。

答案 1 :(得分:3)

String.Remove(Int32, Int32)将完成这项工作:

string temp = "some string contains text which contains demo";
string result = temp.Remove(12,8);

答案 2 :(得分:3)

这是使用正则表达式的解决方案:

public string RemainingString(string str, int start, int length)
{
    return Regex.Replace(str, "^(.{" + start+ "})(?:.{" + length + "})(.*)$", "$1$2");
}

答案 3 :(得分:2)

使用string.Remove

public string RemainingString(string orig, int startIndex, int length)
{
    return orig.Remove(startIndex, length);
}

或者 - 连接两个子串 - 直到索引,并在索引+长度(.NET 1.0 / 1.1)之后:

public string RemainingString(string orig, int startIndex, int length)
{
    return orig.Substring(0, startIndex) + 
           orig.Substring(startIndex + length);
}

答案 4 :(得分:0)

   $line_string = 'this is all the sting from which i would want to treat';

    $key_string ='from which';

    //use strpos

    $position2 = strpos($line_string,$key);

   if($position2){

      $found = substr($line_string,$position2,strlen($key_string));

      //echo $found;

    }

    //the substr now begins at character position $position2

    //and ends at position2 + strlen($key_string);

     //so
     $remainderpos = position2 + strlen($key_string);


     $str_remaining = substr($line_string,$remainderpos);

     echo $str_remaining;

尽可能简单。从头开始的代码。