That's basically what you need to do - or at least, it's the easiest solution. All you'd be "wasting" is the cost of n method invocations - you won't actually be checking any case twice, if you think about it. (IndexOf will return as soon as it finds the match, and you'll keep going from where it left off.)
यहाँ ढांचे विधि का प्रारूप (रों mimicing, एक विस्तार पद्धति के रूप में (ऊपर विचार का) पुनरावर्ती कार्यान्वयन है):
public static int IndexOfNth(this string input,
string value, int startIndex, int nth)
{
if (nth < 1)
throw new NotSupportedException("Param 'nth' must be greater than 0!");
if (nth == 1)
return input.IndexOf(value, startIndex);
var idx = input.IndexOf(value, startIndex);
if (idx == -1)
return -1;
return input.IndexOfNth(value, idx + 1, --nth);
}
इसके अलावा, यहां कुछ (एमबीयूनीट) यूनिट परीक्षण हैं जो माई हैं मदद नहीं आप (यह साबित करने के लिए सही है):
using System;
using MbUnit.Framework;
namespace IndexOfNthTest
{
[TestFixture]
public class Tests
{
//has 4 instances of the
private const string Input = "TestTest";
private const string Token = "Test";
/* Test for 0th index */
[Test]
public void TestZero()
{
Assert.Throws<NotSupportedException>(
() => Input.IndexOfNth(Token, 0, 0));
}
/* Test the two standard cases (1st and 2nd) */
[Test]
public void TestFirst()
{
Assert.AreEqual(0, Input.IndexOfNth("Test", 0, 1));
}
[Test]
public void TestSecond()
{
Assert.AreEqual(4, Input.IndexOfNth("Test", 0, 2));
}
/* Test the 'out of bounds' case */
[Test]
public void TestThird()
{
Assert.AreEqual(-1, Input.IndexOfNth("Test", 0, 3));
}
/* Test the offset case (in and out of bounds) */
[Test]
public void TestFirstWithOneOffset()
{
Assert.AreEqual(4, Input.IndexOfNth("Test", 4, 1));
}
[Test]
public void TestFirstWithTwoOffsets()
{
Assert.AreEqual(-1, Input.IndexOfNth("Test", 8, 1));
}
}
}
पर मूल्य इसी प्रकार है: http://stackoverflow.com/a/9908392/1305911 – JNF
मैं इसके लिए नियमित अभिव्यक्ति का उपयोग करूंगा तो आपको इष्टतम स्ट्रिंग के भीतर स्ट्रिंग से मिलान करने का तरीका। यह एक सुंदर डीएसएल में से एक में हम सभी को जब संभव हो उपयोग करना चाहिए। [एक उदाहरण] (http://www.regular-expressions.info/dotnet.html "लिंक") VB.net में कोड लगभग सी # में समान है। – bovium
मैं नियमित अभिव्यक्ति संस्करण पर अच्छा पैसा रखूंगा "लूपिंग रखें और सरल स्ट्रिंग। इंडेक्सऑफ कर" से सही प्राप्त करने के लिए काफी कठिन है। नियमित अभिव्यक्तियों का स्थान होता है, लेकिन इसका उपयोग तब नहीं किया जाना चाहिए जब सरल विकल्प मौजूद हों। –