我有一个动态字符串值,可能包含这样的值
"Apple ,Banana, , , , Mango ,Strawberry , "
我想像
那样过滤这个字符串"Apple,Banana,Mango,Strawberry".
我已尝试使用以下代码,但它确实有效。
有没有更好的方法在C#(。NET 2.0)中实现相同的目标?
/// <summary>
/// Convert "Comma Separated String" to "Comma Separated String"
/// </summary>
/// <param name="strWithComma">String having values separated by comma</param>
/// <returns>String separated with comma</returns>
private String CommaSeparatedString(String strWithComma)
{
String rtn = String.Empty;
List<String> newList= new List<string>();
if (String.IsNullOrEmpty(strWithComma))
{
return rtn;
}
String[] strArray = strWithComma.Split(",".ToCharArray());
if (strArray == null || strArray.Length == 0)
{
return rtn;
}
String tmpStr = String.Empty;
String separator=String.Empty;
foreach (String s in strArray)
{
if (!String.IsNullOrEmpty(s))
{
tmpStr =s.Replace(Environment.NewLine, String.Empty);
tmpStr = tmpStr.Trim();
if (!String.IsNullOrEmpty(tmpStr))
{
newList.Add(tmpStr);
}
}
}
if (newList != null && newList.Count > 0)
{
rtn = String.Join(",", newList.ToArray());
}
return rtn;
}
答案 0 :(得分:7)
你也可以使用正则表达式:
string str = @"Apple ,,Banana, , , , Mango ,Strawberry , ";
string result = Regex.Replace(str, @"(\s*,\s*)+", ",").TrimEnd(',');
答案 1 :(得分:6)
我相信以下内容应该适用于任何.NET版本:
string[] TrimAll( string[] input )
{
var result = new List<string>();
foreach( var s in input )
result.Add( s.Trim() );
}
return result.ToArray();
}
var delimiters = new [] { ",", "\t", Environment.NewLine };
string result = string.Join(",", TrimAll( input.Split( delimiters, StringSplitOptions.RemoveEmptyEntries ) ) );
编辑:更新以处理空格,制表符和换行符。
答案 2 :(得分:2)
var result = Regex.Replace(strWithComma, ",+", ",").TimEnd(',');
result = Regex.Replace(result, "\s+", string.Empty);
答案 3 :(得分:2)
假设您的商品不包含空格:
private String CommaSeparatedString(String strWithComma)
{
string[] tokens = strWithComma
.Replace(" ", "")
.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
return string.Join(",", tokens);
}
现在我不确定C#2.0是否接受new char[] {','}
语法。如果没有,您可以在其他地方定义数组(例如,作为类私有成员)。
答案 4 :(得分:2)
Regex regex = new Regex(@"\w(?:(?!,| ).)*");
var items = regex.Matches("Apple ,Banana, , , , Mango ,Strawberry , ").Cast<Match>().Select(m => m.Value);
.NET 2.0版
List<string> newList = new List<string>();
Regex regex = new Regex(@"\w(?:(?!,| ).)*");
string str = "Apple ,Banana, , , , Mango ,Strawberry , ";
MatchCollection matches = regex.Matches(str);
foreach (Match match in matches)
{
newList.Add(match.Value);
}
答案 5 :(得分:2)
这是一个单行:
var outputString = string.Join(",", inputString.Replace(" ", string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
答案 6 :(得分:1)
没有正则表达式,没有拆分和连接,修剪等,O(n)时间。 StringBuilder是一个非常好的类来处理字符串。
修改强>
如果字符串不以字母结尾,则会添加逗号。因此添加了额外的TrimEnd(',')
string strWithComma = ",Apple ,Banana, , , , Mango ,Strawberry , \n John,";
var sb = new StringBuilder();
var addComma = false;
foreach (var c in strWithComma )
{
if (Char.IsLetter(c)) // you might want to allow the dash also: example Anne-Marie
{
addComma = true;
sb.Append(c);
}
else
{
if (addComma)
{
addComma = false;
sb.Append(',');
}
}
}
string rtn = sb.ToString().TrimEnd(',');
答案 7 :(得分:0)
警告此方法仅适用于C#3.0或更高版本。对不起,伙计们没有充分阅读这个问题
这可行,但可以更轻松地完成:
string input = "apple,banana,, \n,test\n, ,juice";
var parts = from part in input.Split(',')
let trimmedPart = part.Replace("\n", "")
where !string.IsNullOrWhiteSpace(trimmedPart)
select trimmedPart;
string result = string.Join(",", parts);