views:

167

answers:

6

I have a list of strings like

 A_1
 A_2
 A_B_1
 X_a_Z_14

i need to remove the last underscore and the following characters.

so the resulting list will be like

A
A
A_B
X_a_Z

please post a way to do this

Thanks in advance

+7  A: 
string[] names = {"A_1","A_2","A_B_1","X_a_Z_14" };
for (int i = 0; i < names.Length;i++ )
   names[i]= names[i].Substring(0, names[i].LastIndexOf('_'));
dejavu
+1 but try to post complete, working samples where possible.
Winston Smith
Thanks for the tip. I edited my post.
dejavu
+3  A: 
var s = "X_a_Z_14";
var result = s.Substring(0, s.LastIndexOf('_') ); // X_a_Z
Winston Smith
+2  A: 
input.Substring(0,input.LastIndexOf("_"));
cRichter
+3  A: 
string s = "X_a_Z_14";

s = s.Substring(0, s.LastIndexOf("_"));
Cipi
well done, a sensible answer that works by convention rather than a hardcoded list. +1
Andrew Bullock
+10  A: 
var data = new List<string> {"A_1", "A_2", "A_B_1", "X_a_Z_14"};

int trimPosition;
for (var i = 0; i < data.Count; i++)
         if ((trimPosition = data[i].LastIndexOf('_')) > -1)
            data[i] = data[i].Substring(0, trimPosition);
Ioannis Karadimas
+1 for the only answer that checks the string contains an underscore.
Kobi
...though it will look better with curly braces, and possibly a variable instead of the duplicated `data[i].LastIndexOf('_')`.
Kobi
Agreed, a variable looks cooler. Updated accordingly...
Ioannis Karadimas
i do like "var" too, but var instead of int? cmon.. or is there any benefit i dont see?
atamanroman
Not in the case with "int", but say [ List<string> data = ... ] gets old pretty fast. If there is any performance overhead which I'm not aware of, now that's a different matter... Any pointers to that?
Ioannis Karadimas
+2  A: 

There is also the possibility to use regular expressions if you are so-inclined.

Regex regex = new Regex("_[^_]*$");
string[] strings = new string[] {"A_1", "A_2", "A_B_1", "X_a_Z_14"};
foreach (string s in strings)
{
    Console.WriteLine(regex.Replace(s, ""));
}
executor
Doesn't it little bit overhead to use Regular expressions here ?
Night Walker
@Night Walker - It could be a viable option if you want to throw in some validation, for example, remove only digits: `@"_\d+$"`, or remove the last block of hyphens: `"_+[^_]*$"`, etc. But yes, for a simple scenario you don't need it.
Kobi
this will be "hard" to understand later.. Rename "regex" to "lastUnderscoreAndFollowing" and your co-workers will buy you chocolate. @nightwalker we do this because we CAN ;)
atamanroman
I agree. For the simple case described above it would probably qualify as overkill, but my assumption was that the real problem behind this might be a bit more complex and as Kobi said, this gives you some more flexibility.
executor
note: this could be pretty slow compared to the other solutions
atamanroman
@fielding. Rename "regex" to "firstPlusAndPreceding" and your co-workers will buy you chocolate, with poison in it! ;-)
Guge