简体   繁体   中英

how to remove special char from the string and make new string?

I have a string 4(4X),4(4N),3(3X) from this string I want to make string 4,4,3 . If I am getting the string 4(4N),3(3A),2(2X) then I want to make my string 4,3,2 .

Please someone tell me how can I solve my problem.

This Linq query selects substring from each part of input string, starting from beginning till first open brace:

string input = "4(4N),3(3A),2(2X)";
string result = String.Join(",", input.Split(',')
                                  .Select(s => s.Substring(0, s.IndexOf('('))));
// 4,3,2

This may help:

string inputString = "4(4X),4(4N),3(3X)";
string[] temp = inputString.Split(',');
List<string> result = new List<string>();

foreach (string item in temp)
{
    result.Add(item.Split('(')[0]);
}

var whatYouNeed = string.Join(",", result);

You can use regular expressions

String input = @"4(4X),4(4N),3(3X)";
String pattern = @"(\d)\(\1.\)";
// ( ) - first group.
// \d - one number
// \( and \) - braces.
// \1 - means the repeat of first group.
String result = Regex.Replace(input, pattern, "$1");
// $1 means, that founded patterns will be replcaed by first group
//result = 4,4,3

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