简体   繁体   中英

String Formatting: remove the last underscore and the following characters

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
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);
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('_'));
var s = "X_a_Z_14";
var result = s.Substring(0, s.LastIndexOf('_') ); // X_a_Z
string s = "X_a_Z_14";

s = s.Substring(0, s.LastIndexOf("_"));
input.Substring(0,input.LastIndexOf("_"));

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, ""));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM