convert string array to string

后端 未结 9 2127
野性不改
野性不改 2020-12-02 10:59

I would like to convert a string array to a single string.

string[] test = new string[2];
test[0] = \"Hello \";
test[1] = \"World!\";

I wou

相关标签:
9条回答
  • 2020-12-02 11:14

    Try:

    String.Join("", test);
    

    which should return a string joining the two elements together. "" indicates that you want the strings joined together without any separators.

    0 讨论(0)
  • 2020-12-02 11:20

    Aggregate can also be used for same.

    string[] test = new string[2];
    test[0] = "Hello ";
    test[1] = "World!";
    string joinedString = test.Aggregate((prev, current) => prev + " " + current);
    
    0 讨论(0)
  • 2020-12-02 11:22

    Like this:

    string str= test[0]+test[1];
    

    You can also use a loop:

    for(int i=0; i<2; i++)
        str += test[i];
    
    0 讨论(0)
  • 2020-12-02 11:23

    A slightly faster option than using the already mentioned use of the Join() method is the Concat() method. It doesn't require an empty delimiter parameter as Join() does. Example:

    string[] test = new string[2];
    test[0] = "Hello ";
    test[1] = "World!";
    
    string result = String.Concat(test);
    

    hence it is likely faster.

    0 讨论(0)
  • 2020-12-02 11:24
    string[] test = new string[2];
    
    test[0] = "Hello ";
    test[1] = "World!";
    
    string.Join("", test);
    
    0 讨论(0)
  • 2020-12-02 11:25

    A simple string.Concat() is what you need.

    string[] test = new string[2];
    
    test[0] = "Hello ";
    test[1] = "World!";
    
    string result = string.Concat(test);
    

    If you also need to add a seperator (space, comma etc) then, string.Join() should be used.

    string[] test = new string[2];
    
    test[0] = "Red";
    test[1] = "Blue";
    
    string result = string.Join(",", test);
    

    If you have to perform this on a string array with hundereds of elements than string.Join() is better by performace point of view. Just give a "" (blank) argument as seperator. StringBuilder can also be used for sake of performance, but it will make code a bit longer.

    0 讨论(0)
提交回复
热议问题