开发者

How to truncate a string in .net

Given the string: /Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx

I want to remove all trailing characters after the third /, such that the result is: /Projects/Multiply_Amada/

I wo开发者_如何学编程uld like to do this without using Split or Charindex.


OK, your requirements are a bit tough. So, what about this:

string RemoveAfterThirdSlash(string str)
{
    return str.Aggregate(
            new {
                sb = new StringBuilder(),
                slashes = 0
            }, (state, c) => new {
                sb = state.slashes >= 3 ? state.sb : state.sb.Append(c),
                slashes = state.slashes + (c == '/' ? 1 : 0)
            }, state => state.sb.ToString()
        );
}

Console.WriteLine(RemoveAfterThirdSlash("/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx"));


string str = "/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx";

string newStr = str.SubString(0,24);

I suppose that answers your question!


This code acheives what you need, but I would prefer doing it in 1 lines using the available .NET methods

string str = "/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx";

int index = 0;
int slashCount = 0;

for (int i = 0; i < str.Length; i++)
{
    if (str[i] == '/' && slashCount < 3)
    {
        index = i;
        slashCount++;
    }
}

string newString = str.Substring(index + 1);


Because you are working with paths, you can do this:

    Public Function GetPartialPath(ByVal input As String, ByVal depth As Integer) As String

        Dim partialPath As String = input
        Dim directories As New Generic.List(Of String)

        Do Until String.IsNullOrEmpty(partialPath)
            partialPath = IO.Path.GetDirectoryName(partialPath)
            directories.Add(partialPath)
        Loop

        If depth > directories.Count Then depth = directories.Count

        Return directories.ElementAt(directories.Count - depth)

    End Function

Not tested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜