开发者

String manipulation in C# to increment a number

I'm using .net 2.0 and I have the following string

string 1 = "test (10)"
开发者_高级运维

I have a regular expression that strips the number 10 from the string, I then want to increment it and insert this into the parenthesis of the previous string to create a new strings so:

string 2 = "something else(11)"


If the string is always going to have the same format, you can do it like this:

int myNumber = 11;
string two = String.Format("test ({0})", myNumber);

This is assuming you already have the RegExp as you say in your question, and have incremented it by 1.

EDIT

New example according to your new information:

int myNumber = 11;
int myNewString = "Test";
string two = String.Format("{0} ({1})", myNewString, myNumber);


I don't know what you want to do ... but KEEP IT SIMPLE

var value = ExtractValue(str1);
value++;
string str2 = "test (" + value + ")";


Let a Class handle it..something like this.

TestNumbers testNumbers = new TestNumbers(1); testNumbers.Increment(1); testNumbers.GetNumber(); testNumbers.ToString();

    public class TestNumbers
    {
        private int number = 0;

        public TestNumbers(int number)
        {
            this.number = number;
        }

        public override string ToString()
        {
            return "Test (" + number + ")";
        }

        public void Increment(int incrementStep)
        {
            number += incrementStep;
        }

        public int GetNumber()
        {
            return number;
        }
    }


A simple regex solution might be:

string inputString = "test (10)";

Regex regex = new Regex(@"(.+)\((?<Digit>\d+)\)");
Match match = regex.Match(inputString);

int i = Convert.ToInt32(match.Groups["Digit"].Value);
i++;

string replacePattern = "$1(" + i + ")";
string newString = regex.Replace(inputString, replacePattern);

Console.WriteLine(newString);


you do with following code:

String s1 = string.format("{0} ({1})",yourstring,value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜