-4

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 would like to do this without using Split or Charindex.

Greg
  • 1,480
  • 3
  • 15
  • 29
Anto
  • 1

4 Answers4

2

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"));
Mormegil
  • 7,955
  • 4
  • 42
  • 77
  • how can use aggregate function for string.. it will showing error ('string' does not contain a definition for 'Aggregate' and no extension method 'Aggregate' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)string RemoveAfterThirdSlash(string str) Line 65: { Line 66: return str.Aggregate( Line 67: new Line 68: { – Anto Jun 03 '11 at 14:02
  • Add the System.Linq namespace – markpsmith Jun 03 '11 at 14:23
1
string str = "/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx";

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

I suppose that answers your question!

markpsmith
  • 4,860
  • 2
  • 33
  • 62
0

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);
Devendra D. Chavan
  • 8,871
  • 4
  • 31
  • 35
0

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.

Jeff Paulsen
  • 2,132
  • 1
  • 12
  • 10