0

我在如何修剪这个字符串时遇到了麻烦。我希望删除最后一个“/”之后的所有内容,但是有多个“/”。

例子:

从:http://stackoverflow.com/questions/ask/randomcrap.html

至:http://stackoverflow.com/questions/ask/

4

9 回答 9

10

可以使用许多内置的字符串 utlitites 来完成字符串修剪。

首先你想要LastIndexOf字符串中的“/”字符,然后你想要使用Substring0(字符串开头)的索引到/字符索引的方法。/现在,如果您想包含必须添加一个索引的斜线,这会将所有内容返回到最后。

        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()方法将字符串中从位置开始的所有字符解析0index+1.

于 2013-07-28T00:45:19.827 回答
3

我会使用正则表达式替换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"

我更喜欢对这样的任务使用正则表达式——因为发现它更简单,并且可以“免费”避免额外的条件保护——但请确保了解所使用方法的机制。

于 2013-07-28T00:45:56.083 回答
2

结合起来string.Substring应该string.LastIndexOf可以解决问题。

于 2013-07-28T00:45:11.027 回答
2

我认为你可以通过使用 Uri 类来做到这一点

Uri parent = new Uri(uri, ".");
于 2013-07-28T01:21:05.737 回答
1

最简单的方法可能是

string myURL = "http://stackoverflow.com/questions/ask/randomcrap.html";
string str = myURL.Substring(0, myURL.LastIndexOf('/'));
Console.WriteLine(str);

这将输出

http://stackoverflow.com/questions/ask
于 2013-07-28T00:56:28.857 回答
0

您可以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);

于 2013-07-28T00:42:57.217 回答
0

你可以像这样使用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);
于 2013-07-28T00:45:22.943 回答
0
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/
于 2013-07-28T01:15:08.843 回答
0

如果要找出最后一个'/' 字符,只需使用 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/
于 2013-07-28T06:15:49.620 回答