0

我需要将字符串“*”连接到数组中的一个字符。

例如:

 int count=5;
 string asterisk="*";
  char p[0]='a';
  char p[1]='b';
  char p[2]='a';
  char p[3]='b';
  char p[4]='b';
 for(int i=0;i<count;i++)
 {
   asterisk=asterisk+"*";
  }
   p[0]=p[0]+asterisk;

我怎样才能做到这一点?我希望结果像“ a*****

4

5 回答 5

3

您不能将字符串连接到字符。字符串是字符的集合,不会“适合”单个字符。

你可能想要类似的东西

char asterisk = '*';
string []p = new string[] { "a", "b", "a", "b" };

p[0] = p[0] + new string(asterisk, count);
于 2009-07-19T06:56:11.967 回答
3

通常,这应该使用 a 来完成,这样可以StringBuilder提供更好的性能(取决于您的代码以及您运行它的次数)。
此外,String 有一个构造函数,它接受一个字符和一个数字,并在一个字符串中给出该字符 n 次:http: //msdn.microsoft.com/en-us/library/aa331867%28VS.71%29.aspx
第三, 看看String.ToCharArray, 如

char[] chars = "abcd".ToCharArray();

这可以为您节省一些行数。

于 2009-07-19T06:58:01.713 回答
1

您的示例对我来说看起来不像有效的 c#。如果您要做的只是在字符串末尾连接一堆星号,这应该可以:

string myString = "a";

for(int x = 0; x < 5; x++){
    myString += "*";
}

//myString should now equal "a*****"
于 2009-07-19T06:54:04.420 回答
1

您试图将结果字符串存储在同一个char数组中,这是不可能的,因为在一个 char 变量中您只能存储一个字符,您应该使用 astring[]或 aList<string>来存储结果...

List<string> result = new List<string>();
string asterisk  = new string('*', 5); // Get a string with five * 

foreach (char c in charArray)
{
    result.Add(c + asterisk);
}

或者,如果您有权访问 Linq to Objects:

var result = charArray.Select(c => c + asterisk); // Select all
                                                  // chars and concatenate
                                                  // the  variable
于 2009-07-19T06:55:40.250 回答
1

我认为问题在于“连接”这个词。我认为他想覆盖。所以他可以显示一个半密码,如字符串......

char[] p = { 'a', 'b', 'a', 'b', 'b' };
char[] asterisks = (new String('*', p.Length -1)).ToCharArray();
asterisks.CopyTo(p, 1);

.CopyTo() 会将“星号”数组写入“p”数组。以前的海报是正确的,您应该使用 StringBuilder 进行这样的操作,但是如果您必须将它作为一个字符数组,这就是这样做的方法。(假设我明白你想要什么。“我希望结果像“a*****”。”)

于 2009-07-19T07:17:55.243 回答