.net - C# Method to return the part of string -


i using c# .net 2.0.

i have got below string me

string str = "tcm:0-433-1"; 

now want create method in c#, take above string input parameter , return "tcm:433-".

please suggest best way it!

update: here's bit of nutty idea. 1 possible way of describing desired input/output (to me) this: want take , including : character, skip through first - character, take again through following - character.

generalizing idea, came following mess:

// awful name, obviously. public static string takeskiptakeetc(this string source, params char[] tokens) {     bool taking = true;      int startindex = 0;     stringbuilder stringbuilder = new stringbuilder();     foreach (char token in tokens)     {         int index = source.indexof(token, startindex);         if (index == -1)         {             if (taking)             {                 stringbuilder.append(source.substring(startindex));             }              return stringbuilder.tostring();         }          if (taking)         {             int length = index + 1 - startindex;             stringbuilder.append(source.substring(startindex, length));         }          startindex = index + 1;         taking = !taking;     }      return stringbuilder.tostring(); } 

this extension method on string takes variable number of char arguments, uses employ same logic (take through a, skip through b, take through c, etc.) arguments.

so, example:

console.writeline("tcm:0-433-1".takeskiptakeetc(':', '-', '-')); 

the above outputs:

tcm:433- 

is overly complex solution problem? likely. hey, fun little challenge (i don't enough of these days).


so, given particular input , desired output, like:

return str.substring(0, 4) + str.substring(6, 4); 

obviously, shaky solution requires input match specific format (at least, needs 10 characters long). if input going dynamic such rigid approach, might consider using string.indexof search key split characters or possibly regex class (yikes!) achieve desired result.

in particular case use string.indexof find location of first - character , string.substring take portion of string index.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -