开发者

Adding numbers to a string?

I have strings that look like "0开发者_高级运维1", "02". Is there an easy way that I can change the string into a number, add 1 and then change it back to a string so that these strings now look like "02", "03" etc. I'm not really good at C# as I just started and I have not had to get values before.


To get from a string to an integer, you can youse int.Parse():

int i = int.Parse("07");

To get back into a string with a specific format you can use string.Format():

strings = string.Format("{0:00}",7);

The latter should give "07" if I understand http://www.csharp-examples.net/string-format-int/ correctly.


You can convert the string into a number using Convert.ToInt32(), add 1, and use ToString() to convert it back.

int number = Convert.ToInt32(originalString);
number += 1;
string newString = number.ToString();


Parse the integer

int i = int.Parse("07");

add to your integer

i = i + 1;

make a new string variable and assign it to the string value of that integer

string newstring = i.ToString();


AddStringAndInt(string strNumber, int intNumber)  
{
    //TODO: Add error handling here
    return string.Format("{0:00}", (int.TryParse(strNumber) + intNumber));
}


static string StringsADD(string s1, string s2)
{
    int l1 = s1.Count();
    int l2 = s2.Count();

    int[] l3 = { l1, l2 };
    int minlength = l3.Min();
    int maxlength = l3.Max();
    int komsu = 0;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < maxlength; i++)
    {

        Int32 e1 = Convert.ToInt32(s1.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
        Int32 e2 = Convert.ToInt32(s2.PadLeft(maxlength, '0').ElementAt(maxlength - 1 - i).ToString());
        Int32 sum = e1 + e2 + komsu;
        if (sum >= 10)
        {
            sb.Append(sum - 10);
            komsu = 1;
        }
        else
        {
            sb.Append(sum);
            komsu = 0;
        }
        if (i == maxlength - 1 && komsu == 1)
        {
            sb.Append("1");
        }

    }

    return new string(sb.ToString().Reverse().ToArray());
}

I needed to add huge numbers that are 1000 digit. The biggest number type in C# is double and it can only contain up to 39 digits. Here a code sample for adding very huge numbers treating them as strings.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜