给出字符串:/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx
我想在第三个/
之后删除所有尾随字符,结果是:/Projects/Multiply_Amada/
我想在不使用Split或Charindex的情况下这样做。
答案 0 :(得分:2)
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"));
答案 1 :(得分:1)
string str = "/Projects/Multiply_Amada/MultiplyWeb/Shared/Home.aspx";
string newStr = str.SubString(0,24);
我想这可以回答你的问题!
答案 2 :(得分:0)
此代码可以实现您的需求,但我更喜欢使用可用的.NET方法在一行中完成
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);
答案 3 :(得分:0)
因为您正在使用路径,所以可以这样做:
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
未经测试。