如何使用子字符串拆分字符串
尝试这种情况:
string toSplit= "/Test1/Test2";
toSplit.Split('/');
或
toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);
分裂,后者将删除空字符串。
添加.Last()
会让你最后一个项目。
例如
toSplit.Split('/').Last();
SplitOptions.RemoveEmptyEntries:P或类似的东西我忘记了确切的名字,以摆脱你会得到的第一个/ –
是的,你是对的 –
使用.Split和LINQ的一点点,你可以做以下
string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();
否则,你可以做
string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
desiredValue = str.Substring(str.LastIndexOf("/") + 1);
感谢二进制自找烦恼,忘记了你想要丢掉'/',防守栅栏杆
字符串desiredValue = str.Substring(str.LastIndexOf(“ /“)+ 1);'因为你不想要分隔符? –
使用.Split()。
string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2
这个网站有不少的examples of splitting strings in C#。值得一读。
string [] arr = string1.split('/'); string result = arr [arr.length - 1];
string [] split = words.Split('/');
这会给你一个包含“”,“Test1”和“Test2”的数组split
。
如果你只是想Test2的部分,试试这个:
string fullTest = "/Test1/Test2";
string test2 = test.Split('/').ElementAt(1); //This will grab the second element.
string inputString = "/Test1/Test2";
string[] stringSeparators = new string[] { "/Test1/"};
string[] result;
result = inputString.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write("{0}",s);
}
OUTPUT : Test2
看看string.Split()方法。 – Maggie