SORU
26 EYLÜL 2008, Cuma


Nasıl bir dize *ilk örnek* değiştir .NET?

Belirli bir dize içinde ilk geçtiği yerde değiştirmek istiyorum.

Bunu nasıl yapabilirim .NET?

CEVAP
26 EYLÜL 2008, Cuma


string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos)   replace   text.Substring(pos   search.Length);
}

Örnek:

string str = "The brown brown fox jumps over the lazy dog";

str = ReplaceFirst(str, "brown", "quick");

EDİT: mentioned, itsmatt @olarak da Düzenli ifade var.Replace(String, String, Int32), hangi, aynı, ama muhtemelen daha pahalı çalışma zamanında beri kullanan bir tam özellikli ayrıştırıcı nerede benim yöntem mi bulmak ve üç dize birbirine bağlanması.

EDİT2: Eğer bu ortak bir görev ise, bu yöntemi bir uzantı yöntemi yapmak isteyebilirsiniz:

public static class StringExtension
{
  public static string ReplaceFirst(this string text, string search, string replace)
  {
     // ...same as above...
  }
}

Şimdi Olası yazarken yukarıdaki örneği kullanarak:

str = str.ReplaceFirst("brown", "quick");

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • B3ASTTY™

    B3ASTTY™

    27 Mayıs 2013
  • Dom Esposito

    Dom Esposito

    26 Mayıs 2011
  • lilstevie89

    lilstevie89

    25 Mart 2011