如何找到特定字符的子字符串?我想要的是找到类似于以下内容的子串:
172.20.9.93\randDir
Run Code Online (Sandbox Code Playgroud)
如果"\"存在,我想要IPAddress,或者换句话说,直到"\"的所有内容.有没有办法用substring做这个或有更好的方法来做到这一点?
如果"\"存在,我想要IPAddress,或者换句话说,直到"\"的所有内容.
两种选择:
找到第一个\使用的索引IndexOf,然后使用Substring
int firstSlash = text.IndexOf('\\');
string ipAddress = firstSlash == -1 ? text : text.Substring(0, firstSlash);
Run Code Online (Sandbox Code Playgroud)通过\使用拆分String.Split,然后采取第一部分
string ipAddress = text.Split('\\')[0];
Run Code Online (Sandbox Code Playgroud)