Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Simplest way to remove first occurrence of a substring from another string

Tags:

string

c#

I need to remove the first (and ONLY the first) occurrence of a string from another string.

Here is an example replacing the string "\\Iteration". This:

 ProjectName\\Iteration\\Release1\\Iteration1 

would become this:

 ProjectName\\Release1\\Iteration1 

Here some code that does this:

const string removeString = "\\Iteration"; int index = sourceString.IndexOf(removeString); int length = removeString.Length; String startOfString = sourceString.Substring(0, index); String endOfString = sourceString.Substring(index + length); String cleanPath = startOfString + endOfString; 

That seems like a lot of code.

So my question is this: Is there a cleaner/more readable/more concise way to do this?

like image 843
Vaccano Avatar asked Feb 04 '10 17:02

Vaccano


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


1 Answers

int index = sourceString.IndexOf(removeString); string cleanPath = (index < 0)     ? sourceString     : sourceString.Remove(index, removeString.Length); 
like image 133
LukeH Avatar answered Nov 16 '22 04:11

LukeH