0

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?

1
  • You are not allowed to modify anything in foreach loop 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 standard for loop you wouldn't have to worry about this. Commented Sep 11, 2019 at 20:07

4 Answers 4

4

i don't understand if it's a requirement to use foreach loop but we can do it directly using Replace method on String class:

value = value.Replace(" ", "%20");

This will give you your string value replace with %20 for whitespaces in the string.

Sign up to request clarification or add additional context in comments.

1 Comment

This will be the best approach if you need to change only one character, but if I haven't misunderstood the question, the OP needs to check for many characters and with this you need to call Replace for each character to change
2

You can do it like this:

if(character == ' ')
    encodedValue += "%20";
else
    encodedValue += character;

and you can do the same for all other desired characters.

5 Comments

Can you explain why this works? This answers my question, thanks!
I check every character, if it is something to be replaced, like space, I add its replacement to encodedValue, otherwise I add this character. You can even create two arrays of characters to be replaced and replacements. This will be more efficient.
And at each loop you create a new string. If this call is inside a loop this will create a lot of memory fragmentation because at each loop a new string needs to be created in memory.
@Steve I don't think so. It is the same string encodedValue.
No, += will create a new string that is reassigned to the same variable.
2

First thing to say is that strings are immutable. The call to Replace creates a new string, it doesn't change the input string, so you need to get back the return value from Replace and use it to the following loops, but, if you really want to ignore existing libraries that will do this for you, then I think the best approach is using a StringBuilder to avoid creating continuosly new strings at each loop.

static string Encode(string value)
{
    StringBuilder encodedValue = new StringBuilder();
    foreach (char character in value.ToCharArray())
    {
        if (character == ' ')
            encodedValue.Append("%20");
        else if(......)
            encodedValue.Append("...");
        else
            encodedValue.Append(character);
    }
    return encodedValue.ToString();
}

Comments

0

You could use the LINQ's Select function. It iterates through every value on an array and applies a function to it, returning a new array with the updated values:

var charArray = value.ToCharArray();
var convertedCharArray = charArray.Select((c) => {
    //Here you can apply as many clauses as you like to
    if (c == ' ')
        return "%20";

    return c.ToString();
});
string encodedValue = string.Join("", convertedCharArray);

return encodedValue;

Or, if you wanna go a one liner:

string encodedValue = string.Join("", value.ToCharArray().Select((c) => {
    //Here you can apply as many clauses as you like to
    if (c == ' ')
        return "%20";

    return c.ToString();
}));

return encodedValue;

PS: Always remember to join your char array in a string with string.Join. I keep forgetting it.

Hope to have helped!

1 Comment

Actually it should work if I returned only a string, so the only thing missing is the toString method on the last return call. Thanks for pointing it out, I'll update my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.