我在如何修剪这个字符串时遇到了麻烦。我希望删除最后一个“/”之后的所有内容,但是有多个“/”。
例子:
从:http://stackoverflow.com/questions/ask/randomcrap.html
至:http://stackoverflow.com/questions/ask/
可以使用许多内置的字符串 utlitites 来完成字符串修剪。
首先你想要LastIndexOf字符串中的“/”字符,然后你想要使用Substring从0(字符串开头)的索引到/字符索引的方法。/现在,如果您想包含必须添加一个索引的斜线,这会将所有内容返回到最后。
        static string getToLastSlash(string inString)
        {
            var index = inString.LastIndexOf('/');
            if (index == -1)
                throw new Exception("/ not found in string");
            return inString.Substring(0, index + 1);
        }
该LastIndexOf()方法将返回提供的特定字符或字符串的最后一个索引。如果该LastIndexOf()方法不评估匹配结果将是-1. 鉴于您可能有不匹配的事实,您必须首先检查匹配结果是否为-1. 在上述方法中,我们只是抛出一个异常,但是您的应用程序可能有另一种方法来处理这种情况。
如果匹配大于,-1那么您可以假设找到了匹配。找到匹配项后,您可以使用该Substring()方法将字符串中从位置开始的所有字符解析0为index+1.
我会使用正则表达式替换为end( $) 锚点。
var res = Regex.Replace(input,
    @"[^/]+$", // match all the non-slashes anchored to the end of input
    "");       // replace any matched characters with nothing
// and make sure to use "res"
我更喜欢对这样的任务使用正则表达式——因为我发现它更简单,并且可以“免费”避免额外的条件保护——但请确保了解所使用方法的机制。
结合起来string.Substring应该string.LastIndexOf可以解决问题。
我认为你可以通过使用 Uri 类来做到这一点
Uri parent = new Uri(uri, ".");
最简单的方法可能是
string myURL = "http://stackoverflow.com/questions/ask/randomcrap.html";
string str = myURL.Substring(0, myURL.LastIndexOf('/'));
Console.WriteLine(str);
这将输出
http://stackoverflow.com/questions/ask
您可以Split将 char'/'然后将其转换为 aList<string>并删除最后一项,最后使用string.Join
var url = "http://stackoverflow.com/questions/ask/randomcrap.html";
var b = url.Replace("http://", "").Split('/').ToList(); //replace "html://" to avoid problems with the split
b.RemoveAt(b.Count-1); //last index
var result = "http://" + string.Join("/", b) + "/";
result等于"http://stackoverflow.com/questions/ask/"
这将允许您删除您想要的任何部分。
别忘了你也可以使用b.RemoveRange(int index, int count);
你可以像这样使用LastIndexOf
string str = "http://stackoverflow.com/questions/ask/randomcrap.html";
string final = RemoveAfterLastChar(str, '/');
public string RemoveAfterLastChar(string input, char c)
{
    var index = input.LastIndexOf(c);
    if (index != -1)
        return input.Substring(0, index + 1);
    else
        return input;
}
或者,如果格式始终与您的示例相同,则可以使用Path.GetDirectoryName。
input = Path.GetDirectoryName(input);
void Main()
{   
    Console.WriteLine (TrimLastPart("http://stackoverflow.com/questions/ask/randomcrap.html"));
    Console.WriteLine (TrimLastPart("http://stackoverflow.com/questions/ask//randomcrap.html"));
}
enum State
{
    SlashNotEncountered,
    SlashEncountered,
    BuildingResult
}
string TrimLastPart(string input)
{
    string result = string.Empty;
    State state = State.SlashNotEncountered;    
    foreach (var c in input.ToCharArray().Reverse())
    {
        switch (state)
        {
            case State.SlashNotEncountered:
                if(c == '/')
                {
                    state = State.SlashEncountered;
                }
                break;  
            case State.SlashEncountered:
                if(c != '/')
                {
                    state = State.BuildingResult;
                    result = c.ToString();
                }
                break;  
            case State.BuildingResult:
                result = c + result;
                break;
        }
    }
    return result + "/";
}
输出:
http://stackoverflow.com/questions/ask/
http://stackoverflow.com/questions/ask/
如果要找出最后一个'/' 字符,只需使用 String LastIndexOf方法:
  String text = @"http://stackoverflow.com/questions/ask/randomcrap.html";
  String result = text;
  int index = text.LastIndexOf('/'); // <- last '/' if any
  if (index >= 0) // <- if there's '/' within the string, trim it 
    result = text.Substring(0, index + 1);
  ...
  Console.Out.Write(result); // <- http://stackoverflow.com/questions/ask/