Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Do-Loop not adding Characters to a string

Tags:

c#

Ok, I have this string Player.Character with this in it "Average Man{[Attributes (Mind 10) (Body 10) (Soul 10)]}".

And I have this do-loop set up so that it should be going through this string 1 character at a time and seeing if its this "[" while adding each character it checks to another string ContainerName. The thing is ContainerName only has this in it "[" and I want it should have "Average Man{".

If some one could help me understand why it that this is happening and possibly a solution that my amature mind could handle I would be most gracious.

O ya, here be my code.

int count = -1;

string ContainerName = "";

//Finds Start of container
do
{
    count = count + 1;
    ContainerName = ContainerName + Player.Character[count].ToString();
} while (Player.Character[count].ToString() != "[" && 
         Player.Character.Length - 1 > count);

textBox1.Text = ContainerName;
like image 703
Matt Pruent Avatar asked Dec 20 '12 15:12

Matt Pruent


2 Answers

Your code works fine (I just tested it). ContainerName will have value "Average Man{[". Player.Charecter probably doesn't have the right value. I used Player.Charecter = "Average Man{[Attributes (Mind 10) (Body 10) (Soul 10)]}"

A more elegant solution would be

TextBox1.Text = Player.Character.Substring(0, Player.Character.IndexOf('['))
like image 80
anthonybell Avatar answered Oct 16 '22 16:10

anthonybell


I'm assuming Character is a string property of Player, and you want the string up to the first [ or the entire string if it doesn't exist.

StringBuilder sb = new StringBuilder();
foreach (char c in Player.Character)
{
    if (c == '[')
        break;
    sb.Append(c);
}
textBox1.Text = sb.ToString();

or

var i = Player.Character.IndexOf('[');
textBox1.Text = i >= 0 ? Player.Character.Substring(0, i) : Player.Character;
like image 45
snurre Avatar answered Oct 16 '22 15:10

snurre