簡體   English   中英

如何從字符串中刪除特殊字符並創建新字符串?

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

我從這個字符串中得到一個字符串4(4X),4(4N),3(3X)我想使字符串4,4,3 如果我得到字符串4(4N),3(3A),2(2X)那么我要使字符串4,3,2

請有人告訴我如何解決我的問題。

這個Linq查詢從輸入字符串的每個部分中選擇子字符串,從開始到第一個大括號開始:

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

這可能會有所幫助:

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);

您可以使用正則表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM