I am trying to make a application that makes all the first letters to capital letters and the others to small.
string navn = txtNavn.Text;
string delnavn1, delnavn2;
delnavn1 = navn.Substring(0, 1).ToUpper();
delnavn2 = navn.Substring(1).ToLower();
navn = delnavn1 + delnavn2;
if (navn.Contains(" "))
{
for (int i = 0; i < navn.Length; i++)
{
if (navn.Substring(i, 1) == " ")
{
delnavn1 = navn.Substring(i, 1).ToUpper();
delnavn2 = navn.Substring(i + 2).ToLower();
navn += delnavn1 + delnavn2 + " ";
}
}
}
else
{
delnavn1 = navn.Substring(0, 1).ToUpper();
delnavn2 = navn.Substring(1).ToLower();
navn = delnavn1 + delnavn2;
}
txbMelding.Text = "Du heter " + navn;
Sorry for weird variablenames, I am norwegian and did not have enough time to change them.
I suspect this is the immediate problem:
navn += delnavn1 + delnavn2 + " ";
You're concatenating with the previous value of navn
. So if you start off with "Hello there", when you get to the first space you'll have:
delnavn1 = " "
delnavn2 = "There"
navn = "Hello there" + delnavn1 + delnavn2;
i.e. navn = "Hello there There"
.
Here's a rather simpler approach:
char[] text = txtNavn.Text.ToCharArray();
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
text[i] = i == 0 || text[i - 1] == ' '
? char.ToUpper(c)
: char.ToLower(c);
}
txbMelding.Text = "Du heter " + new string(text);
Replacing the letters in an array "in place" is much simpler than messing around with strings concatenation and substrings.
Note that this is still a very crude way of performing title-casing - you should probably look at TextInfo.ToTitleCase
for a more comprehensive culture-sensitive code (and code that you don't need to write yourself!)
See more on this question at Stackoverflow