繁体   English   中英

更改字符串的特定部分

[英]Changing a specific part of a string

在C#中,我得到了一个字符串,其格式如下:

a number|a number|a number,a number

例如:1 | 2 | 3,4

我认为每个数字都是字符串的不同部分。 在前面的示例中,1是第一部分,2是第二部分,依此类推。

给定要更改的部分的索引,我希望能够替换字符串的特定部分。

String.Split做到这一点并不难,但是用逗号String.Split部分使它变得乏味,因为那时我需要检查索引是3还是4,然后还要用逗号分开。 有没有更优雅的方法来切换字符串中的特定部分? 也许以某种方式使用正则表达式?

编辑:我将添加一些我以前没有写过的要求:

例如,如果我想取字符串的第三部分并将其替换为数字并添加2,该怎么办?例如1 | 2 | 3,4到1 | 2 | 5,4,其中5不是常数但取决于给定的输入字符串。

您可以创建以下方法

static string Replace(string input, int index, string replacement)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => matchIndex++ == index ? replacement : m.Value);
}

用法:

string input = "1|2|3,4";
string output = Replace(input, 1, "hello"); // "1|hello|3,4

正如Eric Herlitz所建议的,您可以使用其他正则表达式,即定界符的负数。 例如,如果你希望,| 定界符,您可以将\\d+替换为[^,|]+正则表达式。 如果你希望,| #分隔符,可以使用[^,|#]正则表达式。

如果您需要进行一些数学运算,则可以自由进行:

static string Replace(string input, int index, int add)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => matchIndex++ == index ? (int.Parse(m.Value) + add).ToString() : m.Value );
}

例:

string input = "1|2|3,4";
string output = Replace(input, 2, 2); // 1|2|5,4

您甚至可以使其通用:

static string Replace(string input, int index, Func<string,string> operation)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => matchIndex++ == index ? operation(m.Value) : m.Value);
}

例:

string input = "1|2|3,4";
string output = Replace(input, 2, value => (int.Parse(value) + 2).ToString()); // 1|2|5,4

使用Regex.Split作为输入,使用Regex.Match收集定界符

string input = "1|2|3,4,5,6|7,8|9";
string pattern = @"[,|]+";

// Collect the values
string[] substrings = Regex.Split(input, pattern);

// Collect the delimiters
MatchCollection matches = Regex.Matches(input, pattern);

// Replace anything you like, i.e.
substrings[3] = "222";

// Rebuild the string
int i = 0;
string newString = string.Empty;
foreach (string substring in substrings)
{
    newString += string.Concat(substring, matches.Count >= i + 1 ? matches[i++].Value : string.Empty);
}

这将输出"1|2|3,222,5,6|7,8|9"

试试这个(经过测试):

public static string Replace(string input, int value, int index)
{
       string pattern = @"(\d+)|(\d+)|(\d+),(\d+)";

       return Regex.Replace(input, pattern, match =>
       {
            if (match.Index == index * 2) //multiply by 2 for | and , character.
            {
                return value.ToString();
            }

            return match.Value;
      });
 }

用法示例:

string input = "1|2|3,4";
string output = Replace(input, 9, 1);

更新了新要求:

public static string ReplaceIncrement(string input, int incrementValue, int index)
{
            string pattern = @"(\d+)|(\d+)|(\d+),(\d+)";

            return Regex.Replace(input, pattern, match =>
            {
                if (match.Index == index * 2)
                {
                    return (int.Parse(match.Value) + incrementValue).ToString();
                }

                return match.Value;
            });
 }

尝试这个:

    static void Main()
    {
        string input = "1|2|3|4,5,6|7,8|9|23|29,33";

        Console.WriteLine(ReplaceByIndex(input, "hello", 23));
        Console.ReadLine();
    }

    static string ReplaceByIndex(string input, string replaceWith, int index)
    {
        int indexStart = input.IndexOf(index.ToString());

        int indexEnd = input.IndexOf(",", indexStart);
        if (input.IndexOf("|", indexStart) < indexEnd)
            indexEnd = input.IndexOf("|", indexStart);

        string part1 = input.Substring(0, indexStart);
        string part2 = "";
        if (indexEnd > 0)
        {
            part2 = input.Substring(indexEnd, input.Length - indexEnd);
        }

        return part1 + replaceWith + part2;
    }

这是假设数字按升序排列。

暂无
暂无

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

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