Get the index of Nth occurrence of a Char in a String From Start/End

Here’s a quick utility to get the Nth index of a Char in a String using the .NET IndexOf & LastIndexOf methods. Few points regarding this utility.

  • If the Char is not found then, it will return -1.
  • If for a string, say, str, whose value is http://abc.com/xyz, char ‘/’ has occurred only 3 times. So if you would try to get the 4th or higher index of ‘/’, it will always return 14, which is the index of the last occurrence of this char.

Following are the 2 methods that perform this task

private int GetNthIndexFromEnd(string str, int index, char delimeter)
{
	int count = 0;
	int nthIndex = str.Length - 1;
	while (true)
	{
		int nthIndexTemp = str.LastIndexOf(delimeter, nthIndex);
		if (nthIndexTemp > -1)
		{
			++count;
			nthIndex = nthIndexTemp;

			if (count == index)
				break;
			else
				--nthIndex;
		}
		else
		{
			//If the given delimiter is not present
			if (count == 0)
				nthIndex = -1;
			break;
		}
	}
	return nthIndex;
}

private int GetNthIndexFromStart(string str, int index, char delimeter)
{
	int count = 0;
	int nthIndex = 0;
	while (true)
	{
		int nthIndexTemp = str.IndexOf(delimeter, nthIndex);
		if (nthIndexTemp > -1)
		{
			++count;
			nthIndex = nthIndexTemp;

			if (count == index)
				break;
			else
				++nthIndex;
		}
		else
		{
                    //If the given delimiter is not present
                    if (count == 0)
				nthIndex = -1;
			break;
		}
	}
	return nthIndex;
}