簡體   English   中英

拆分逗號分隔的字符串並在 C# 中添加引號 - 優雅的解決方案

[英]split a comma-separated string and add Quotes in C# - elegant solution

我有一個看起來像這樣的string

var v = "10,14,18,21" 

並希望將其用作如下所示的東西:

'10', '14', '18', '21'

我寫了一個 function ,它用逗號分割值並將它們作為字符串加在一起。 另外,我從結果字符串中刪除了最后一個,

我把所有東西都放在一個名為prep for testing 的 function 中。

function 做了,我想讓它做。 但是,我想知道是否有更優雅的方法來實現相同的結果。 這是我想出的:

public static string prep(string s) {
    string res = "";

    List<string> list = s.Split(',').ToList<string>();

    foreach(var item in list) 
        res += "'" + item + "',";

    res = res.TrimEnd(',');

    return res;
}

你考慮過這個嗎?

var v = "10,14,18,21";
var r = $"'{v.Replace(",", "', '")}'";

這給出: '10', '14', '18', '21'

您可以嘗試正則表達式

using System.Text.RegularExpressions;

...

string result = Regex.Replace(v, "[^,]+", " '$0'");

在這里,我們將逗號之間的每個項目包裝成單引號。

編輯:正如 juharr 在評論中指出的那樣,我們在result字符串的開頭有額外的空間 我們既可以

去掉它:

result = Regex.Replace(v, "[^,]+", " '$0'").TrimStart();

或阻止它:

string result = Regex
 .Replace(v, "[^,]+", m => $"{(m.Index > 0 ? " ":"")}'{m.Value}'");

你可以在這里使用string.Join()

var result = string.Join(", ", v.Split(",").Select(x => $"'{x}'"));

Console.WriteLine(result);
// '10', '14', '18', '21'

它基本上通過", "連接項目,然后使用 LINQ 中的Enumerable.Select()在每個字符串周圍投射單引號。

您還可以添加不帶$ - 字符串插值的單引號:

var result = string.Join(", ", v.Split(",").Select(x => "'" + x + "'"));

正如@Racil Hilan在評論中有用地指出的那樣,我們在這里不需要 LINQ 並且可以用"'"包圍結果並加入"', '"

var result = "'" + string.Join("', '", v.Split(",")) + "'";

一種方法是在Split的結果上使用Select ,然后string.Join

public static string prep(string s) {
    var array = s.Split(',');
    // Select takes a lambda that tells it what to do with each item in the array
    var quotesAdded = array.Select(x => $"'{x}'");
    var result = string.Join(", ", quotesAdded);
    return result;
}

或全部在表達式主體成員中:

public static string prep(string s) => string.Join(", ",
    s.Split(',').Select(x => $"'{x}'")
);

只是為了它,我寫了一些代碼來測試這里的各種方法,看看它們如何用不同長度的字符串相互競爭。 隨意添加任何其他變體,以自己找出哪個是最快的,並看看它如何與更大的字符串一起擴展。

注意:我放棄了包含 10,000 個逗號分隔項的字符串,因為 Aggregate 方法需要很長時間才能完成。

private static readonly Random Rand = new Random();

private static void Main(string[] args)
{
    for (int size = 10; size <= 1000; size *= 10)
    {
        var input = GenerateInput(size);

        Console.WriteLine($"Size {size}:");
        Console.WriteLine("Average          Total            Method");
        Tester(input, AddSingleQuotesRegExNotCompiled, nameof(AddSingleQuotesRegExNotCompiled));
        Tester(input, AddSingleQuotesRegExCompiled, nameof(AddSingleQuotesRegExCompiled));
        Tester(input, AddSingleQuotesStringReplace, nameof(AddSingleQuotesStringReplace));
        Tester(input, AddSingleQuotesJoinSplitSelectWithInterpolation, nameof(AddSingleQuotesJoinSplitSelectWithInterpolation));
        Tester(input, AddSingleQuotesJoinSplitSelectWithoutInterpolation, nameof(AddSingleQuotesJoinSplitSelectWithoutInterpolation));
        Tester(input, AddSingleQuotesJoinSplit, nameof(AddSingleQuotesJoinSplit));
        Tester(input, AddSingleQuotesSplitSelectAggregate, nameof(AddSingleQuotesSplitSelectAggregate));

        Console.WriteLine();
    }

    Console.ReadLine();
}


public static void Tester(string input, Func<string, string> func, string name)
{
    var sw = Stopwatch.StartNew();
    for (int i = 0; i < 10000; i++)
    {
        func(input);
    }

    sw.Stop();

    Console.Write($"{sw.Elapsed/10000} {sw.Elapsed} {name}");
    Console.WriteLine();
}

public static string GenerateInput(int count)
{
    var builder = new StringBuilder();
    while (count-- > 0)
    {
        builder.Append(Rand.Next(100));
        if (count > 0)
            builder.Append(',');
    }

    return builder.ToString();
}

private static Regex addComma = new Regex("[^,]+", RegexOptions.Compiled);

public static string AddSingleQuotesRegExCompiled(string input) => 
    addComma.Replace(input, "'$0'");
public static string AddSingleQuotesRegExNotCompiled(string input) => 
    Regex.Replace(input, "[^,]+", " '$0'");
public static string AddSingleQuotesStringReplace(string input) => 
    $"'{input.Replace(",", ", ")}'";
public static string AddSingleQuotesJoinSplitSelectWithInterpolation(string input) => 
    string.Join(", ", input.Split(",").Select(x => $"'{x}'"));
public static string AddSingleQuotesJoinSplitSelectWithoutInterpolation(string input) => 
    string.Join(", ", input.Split(",").Select(x => "'" + x + "'"));
public static string AddSingleQuotesJoinSplit(string input) => 
    "'" + string.Join("', '", input.Split(",")) + "'";
public static string AddSingleQuotesSplitSelectAggregate(string input) => 
    input.Split(',')
        .Select(m => "'" + m + "'")
        .Aggregate((tot,next) => tot + "," + next);
}

結果如下

Size 10:
Average          Total            Method
00:00:00.0000053 00:00:00.0526194 AddSingleQuotesRegExNotCompiled
00:00:00.0000031 00:00:00.0309486 AddSingleQuotesRegExCompiled
00:00:00.0000002 00:00:00.0018592 AddSingleQuotesStringReplace
00:00:00.0000017 00:00:00.0169309 AddSingleQuotesJoinSplitSelectWithInterpolation
00:00:00.0000008 00:00:00.0084822 AddSingleQuotesJoinSplitSelectWithoutInterpolation
00:00:00.0000004 00:00:00.0039672 AddSingleQuotesJoinSplit
00:00:00.0000010 00:00:00.0102010 AddSingleQuotesSplitSelectAggregate

Size 100:
Total            Average          Method
00:00:00.0000239 00:00:00.2394021 AddSingleQuotesRegExNotCompiled
00:00:00.0000163 00:00:00.1628607 AddSingleQuotesRegExCompiled
00:00:00.0000015 00:00:00.0149009 AddSingleQuotesStringReplace
00:00:00.0000065 00:00:00.0650797 AddSingleQuotesJoinSplitSelectWithInterpolation
00:00:00.0000069 00:00:00.0693588 AddSingleQuotesJoinSplitSelectWithoutInterpolation
00:00:00.0000034 00:00:00.0338554 AddSingleQuotesJoinSplit
00:00:00.0000129 00:00:00.1287369 AddSingleQuotesSplitSelectAggregate

Size 1000:
Total            Average          Method
00:00:00.0002089 00:00:02.0892826 AddSingleQuotesRegExNotCompiled
00:00:00.0001607 00:00:01.6066026 AddSingleQuotesRegExCompiled
00:00:00.0000144 00:00:00.1444781 AddSingleQuotesStringReplace
00:00:00.0000578 00:00:00.5776627 AddSingleQuotesJoinSplitSelectWithInterpolation
00:00:00.0000580 00:00:00.5801025 AddSingleQuotesJoinSplitSelectWithoutInterpolation
00:00:00.0000296 00:00:00.2957712 AddSingleQuotesJoinSplit
00:00:00.0005631 00:00:05.6307457 AddSingleQuotesSplitSelectAggregate

解決此問題的另一種方法(不使用 LINQ):

public static string prep(string s) =>
    "'" + string.Join("', '", s.Split(",")) + "'";

我更喜歡使用聚合

    string a = "1,2,3,4,5";
    string c = a.Split(',').Select(m => "'" + m + "'").Aggregate((tot,next) => tot + "," + next);

暫無
暫無

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

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