I'm working on a program that encodes strings to be used in a URL without using a library that will do the encoding for me.
The idea is that a string is passed to this function, each character of the string is iterated through. If the character is okay, it's added to the encoded string. If it fails, it's corrected, then added to the encoded string. My thought was to do multiple if/if-else statements to replace any bad characters, but I can't seem to figure out how to properly do this.
static string Encode(string value)
{
string encodedValue = "";
foreach (char character in value.ToCharArray())
{
if(character == ' ')
value.Replace(character, '%20');
// Add to encodedValue
}
return encodedValue;
}
Obviously this won't work because I can't replace a character with something larger than a character in this way. As an example, what can I do to replace a space in the string with it's code %20?
foreachloop since it's managed by the language and therefore cannot predict what changes you make and you cannot tell it how to predict the changes manually. Therefore, as the answers suggest, you can clone and replace characters in the clone instead of playing with the original. Please keep in mind that in a standardforloop you wouldn't have to worry about this.