string a = "i have an apple";
i want the output to be "I Have An Apple";
i was able to capitalize the first word but can't figure out how to
capitalize every word in that string
Since strings are immutable (for a good reason), you can't say something
like:
a[idx] = Char.ToUpper(a[idx]);
Since this would modify the instance, the assignment can't be made.
You could, on the other hand, assign the variable a to a whole new string
instance (reference):
a = "new string";
However, you aren't actually changing the instance that a referenced before
-- you're simple "pointing" a to a new string instance.
The usual way to work around the immutability problem would be to create a
StringBuilder instance, modify it as desired then return a string from it:
StringBuilder sb = new StringBuilder(a);
sb[idx] = Char.ToUpper(sb[idx]);
a = sb.ToString();
Since StringBuilder instances aren't immutable, you *can* modify them, as
shown.
In this case, though, I would probably just create a StringBuilder instance
and fill it up one character at a time:
/// <summary>
/// Return a copy of the specified string with the first character and
/// any characters following spaces, as upper-case.
/// </summary>
static string MakeIntoTitleCase(string val) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < val.Length; ++i){
if (i == 0 || val[i - 1] == ' ') {
sb.Append(Char.ToUpper(val
));
} else {
sb.Append(val);
}
}
return sb.ToString();
}