How to truncate a string in .net

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

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

I would like to do this without using Split or Charindex.

-4
source share
4 answers

OK, your requirements are a little tight. So how 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")); 
+2
source share
 string str = "/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx"; string newStr = str.SubString(0,24); 

I suppose this answers your question!

+1
source share

This code provides what you need, but I would prefer to do it in 1 line 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); 
0
source share

Since you work 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
source share

All Articles