2012-12-08 53 views
0
string[] string1; 
string string2; 
string1 = string2; 

这总是给我一个错误说我不能转换成stringstring[]。我怎么能够“string2”追加到string1?我必须添加多个string,因此如果有任何方法可以将多个string添加到string1中,我将非常感谢您的帮助!如何追加一个字符串到字符串[],分配不工作

+4

你是不是想将它们连接起来?你想添加一个字符串到一个字符串数组吗? – JoshVarty

+1

请使用对未来访问者更有用的主题行。 –

+0

我想如果你描述你要完成的是什么,而不是谈论你所看到的具体错误,你会得到更多的帮助。正如@Josh所指出的那样,目前还不清楚你实际上想要解决什么问题,我会给出的答案在很大程度上取决于此。 – tvanfosson

回答

1

您试图将单个字符串分配到整个string的数组中。

这是不可能的。

您需要选择要使用的阵列的哪个元素。

更好的是,使用List<string>而不是数组 - 这是一个更好的结构,因为它不受其初始大小的限制。

List<string> string1 = new List<string>(); 
string string2; 
string1.Add(string2); // Will add a null 
+0

非常感谢!这对我来说是一个很大的麻烦。希望现在我终于可以完成我的项目! – Tribenonkey

1

一个可能的解决方案是首先使用列表并将所有字符串存储在那里。然后,作为最后一步,将列表转换为数组。 这是特别合适的,如果你不知道你想在数组中存储的字符串的数量,然后开始存储它们。
但是,这有一些性能影响可能不是最好的可行解决方案取决于你实际上正在尝试做什么。

string string2 = "HelloWorld"; 
List<string> list = new List<string>(); 
list.Add(string2); 
// repeat for all objects 

string[] string1 = list.ToArray(); 
1

创建一个大小两个字符串数组:

string[] string1= new string[2]; 
string string2 = "test"; //You must also assign something to your string before using it. 
string1[0] = string2; 

连接两个字符串:

string string3 = "third"; 
string string4 = "fourth"; 
string string5 = string3 + string4; //string5 is now "thirdfourth" 
0

添加到Array是不平凡的操作......如果你只需要要收集字符串,可以增长使用List<string>,不要忘记创建对象:

List<string> string1 = new List<string>(); 
string string2 = "test"; 
string1.Add(string2); 
0

如果需要用绳子[]工作,并追加元素,像这样做:

 string2 = string1 .Concat(new[] { 
      stringa, stringb,stringc,stringd.... 
     }).ToArray(); 

或单个:

 string2 = string1.Concat(new[]{ string2 }).ToArray(); 
0

string1是一个字符串数组。 string2是一个字符串。

首先创建适当大小

string1 = new string[10]; 

然后通过指定一个索引添加到字符串这个阵列的阵列;

string1[0] = string2; 
string1[1] = "Hello"; 
string1[2] = "World"; 

等等。在此示例中,您可以执行此操作直至string[9],因为索引范围从0到数组大小减1。

如果您事先不知道数组的大小,则可以使用List<string>代替。列表自动增长

var list = new List<string>(); 
list.Add(string2); 
list.Add("Hello"); 
list.Add("World"); 

foreach (string s in list) { 
    Console.WriteLine(s); 
} 

for (int i = 0; i < list.Count; i++) { 
    Console.WriteLine(list[i]); 
}