简体   繁体   English

如何使用foreach循环替换字符串中的字符?

[英]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. 我正在开发一个程序,该程序对要在URL使用的字符串进行编码,而无需使用会为我进行编码的库。

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. 我的想法是执行多个if/if-else语句来替换任何不良字符,但我似乎无法弄清楚如何正确地执行此操作。

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 ? 例如,如何用代码%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 : 我不明白是否需要使用foreach循环,但我们可以使用String类上的Replace方法直接进行操作:

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

This will give you your string value replace with %20 for whitespaces in the string. 这将使您的字符串值用%20替换字符串中的空格。

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. 对Replace的调用将创建一个新字符串,它不会更改输入字符串,因此您需要从Replace取回返回值,并将其用于以下循环,但是,如果您确实想忽略将执行此操作的现有库,这对您来说,那么我认为最好的方法是使用StringBuilder以避免在每个循环中连续创建新的字符串。

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. 您可以使用LINQ的Select函数。 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. PS:永远记得将您的char数组连接到具有string.Join的字符串中。 I keep forgetting it. 我一直忘记它。

Hope to have helped! 希望能有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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