views:

1169

answers:

5

I need to concatenate '*', which is a string, to a character in an array.

For example:

 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;

How can I do this? I want the result to be like "a*****"

+1  A: 

Your example doesn't look like valid c# to me. If all you're trying to do is concatenate a bunch of asterisks at the end of a string, this should work:

string myString = "a";

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

//myString should now equal "a*****"
Pwninstein
+1  A: 

You are trying to store the resulting strings in the same char array, and that is not possible because in one char variable you can only store one char, you should use a string[] or a List<string> to store the result...

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);
}

Or if you have access to Linq to Objects:

var result = charArray.Select(c => c + asterisk); // Select all
                                                  // chars and concatenate
                                                  // the  variable
CMS
+3  A: 

You cannot concatenate a string to a character. A string is a collection of characters, and won't "fit" inside a single character.

You probably want something like

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

p[0] = p[0] + new string(asterisk, count);
Senthil Kumar
+3  A: 

Generally, this should be done using a StringBuilder, that whould give better performances (depending on your code and how many time you run it).
Also, String has a constructor that takes a char and a number, and gives that char n times in a string: http://msdn.microsoft.com/en-us/library/aa331867%28VS.71%29.aspx
Third, have a look at String.ToCharArray, as in

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

This can save you some lines there.

Kobi
+1  A: 

I think the problem is the word "concatenate". I think he wants to overwrite. So he can show a semi-password like string...

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

.CopyTo() will write the "asterisks" array to the "p" array. Previous posters are right in that you should use StringBuilder for manipulation like this, but if you HAVE to have it as an array of chars, this is the way to do it. (Assuming that I understand what you want."I want the result to be like "a*****". ")

William Crim