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

  • 3DS Max Tutorials

    3DS Max Tuto

    4 AĞUSTOS 2013
  • EvilControllers

    EvilControll

    20 Ocak 2008
  • How To Cook That

    How To Cook

    16 NİSAN 2011