简体   繁体   中英

How can I replace a character in a string using a foreach loop?

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 ?

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.

You can do it like this:

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

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

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();
}

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!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM