简体   繁体   中英

Changing a specific part of a string

In C#, I got a string which looks in the following format:

a number|a number|a number,a number

for example: 1|2|3,4

I consider each number as the different part of the string. in the previous example, 1 is the first part, 2 is the second and so on.

I want to be able to replace a specific part of the string given an index of the part I want to change.

It's not that hard to do it with String.Split but that part with the comma makes it tedious since then i need to check if the index is 3 or 4 and then also separate with the comma. Is there a more elegant way to do a switch of a specific part in the string? maybe somehow with a regular expression?

EDIT: I will add some requirements which I didn't write before:

What if I want to for example take the 3rd part of the string and replace it with the number there and add it 2. for example 1|2|3,4 to 1|2|5,4 where the 5 is NOT a constant but depends on the input string given.

You can create the following method

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

Usage:

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

As Eric Herlitz suggested, you can use other regex, the negative of delimiters. For example, if you expect , and | delimiters, you can replace \\d+ by [^,|]+ regex. If you expect , , | and # delimiters, you can use [^,|#] regex.

If you need to do some mathematical operations, you're free to do so:

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

Example:

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

You can even make it generic:

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

Example:

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

Use Regex.Split for the input and Regex.Match to collect your delimiters

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

This will output "1|2|3,222,5,6|7,8|9"

Try this (tested):

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

Usage example:

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

Updated with new requirement:

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

Try this:

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

This is assuming the numbers are in ascending order.

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