I have written a code that should write a Space after every Character. But it dont looks like it is working.
foreach (char c in texttoencodedecode.Text)
{
c += " ";
texttoencodedecode.Text += c
}
Sadly this isnt working. The c += " "; outputs a Error. Hope you can help me Cheers.
The char c
is a single character (and it is something that is fixed, you can't have a zero-length char
, you can't have a two-length char
), so you can't "add" to it. You can't even modify the variable you are doing the foreach
on (so you can't modify texttoencodedecode.Text
), you'll get an Exception
at runtime. The solution is to write to a new temporary variable, temp
and then reassign texttoencodedecode.Text
with temp
string temp = string.Empty;
foreach (char c in texttoencodedecode.Text)
{
temp += c;
temp += " ";
}
texttoencodedecode.Text = temp;
Now... Normally you should use a StringBuilder
for this, because "appending" many times to a string
is "bad" ( string
s aren't built for it):
var sb = new StringBuilder();
foreach (char c in texttoencodedecode.Text)
{
sb.Append(c);
sb.Append(' ');
}
texttoencodedecode.Text = sb.ToString();
A char
can only contain a single character, so attempting to append another character to it will result in an error, unless you convert it to a string.
foreach (char c in texttoencodedecode.Text)
{
string s = c + " ";
texttoencodedecode.Text += s;
}
Or
foreach (char c in texttoencodedecode.Text)
{
texttoencodedecode.Text += (c + ' ');
}
If you want to be clever though you can use linq:
texttoencode.Text = new string( texttoencode.Text.SelectMany( c => new char[] { c, ' '}).ToArray());
This avoids the continuous reallocations of strings.
I, guess you are wanting this,
Input: Hello
output: H ello
Here, c is a character. You are adding space(" ") with c which is not possible.
You can try this way(hint):
Take a empty string(temp)
foreach (char c in texttoencodedecode.Text) {
Add c with temp
Add space with temp
}
Assign texttoencodedecode.Text = temp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.