我正在尝试创建一个函数,该函数返回字符串中给定char的第N次出现的索引.
这是我的尝试:
private int IndexOfNth(string str, char c, int n)
{
int index = str.IndexOf(c) + 1;
if (index >= 0)
{
string temp = str.Substring(index, str.Length - index);
for (int j = 1; j < n; j++)
{
index = temp.IndexOf(c) + 1;
if (index < 0)
{
return -1;
}
temp = temp.Substring(index, temp.Length - index);
}
index = index + (str.Length);
}
return index;
}
Run Code Online (Sandbox Code Playgroud)
这应该找到第一个匹配项,切断字符串的前部,从新的子字符串中找到第一个匹配项,然后打开直到它获得第n个匹配项的索引.但是,我没有考虑最终子字符串的索引将如何偏离原始字符串中的原始实际索引.我该如何工作?
另外作为一个附带问题,如果我想将char作为制表符,我是否通过此函数'\ t'或者什么?
我有以下字符串
string a = @"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
Run Code Online (Sandbox Code Playgroud)
我正在尝试删除部分字符串,所以最后我想留下
string a = @"\\server\MainDirectory\SubDirectoryA\SubdirectoryB";
Run Code Online (Sandbox Code Playgroud)
所以目前我正在做
string b = a.Remove(a.LastIndexOf('\\'));
string c = b.Remove(b.LastIndexOf('\\'));
Console.WriteLine(c);
Run Code Online (Sandbox Code Playgroud)
这给了我正确的结果.我想知道是否有更好的方法来做到这一点?因为我必须在很少的地方做这件事.
注:该SubdirectoryC长度将是未知的.因为它是由用户输入的数字/字母组成的
如何在最后'/'后得到字符串的值
string path=http://localhost:26952/Images/Users/John.jpg
Run Code Online (Sandbox Code Playgroud)
我希望得到类似的结果: John.jpg