Home
Map
Increment String That Contains a NumberConsider an issue with incrementing numbers stored as strings. Use int.Parse and ToString.
C#
This page was last reviewed on Sep 26, 2022.
Increment string, number. Numbers are sometimes stored as strings. How can we increment these numbers? We must convert the strings to numbers to increment them.
String concatenation is not the same thing as incrementing a number. Occasionally programmers make mistakes because of how the string.Concat method works with the plus operator.
Example. We can parse the string "1234" with int.Parse. In the two wrong statements, the number is converted to a string, and then another number is converted to a string and appended.
Tip This is because the plus operator compiles to a call to the method string.Concat.
Then The numbers 1 and 2 are converted to strings and passed to string.Concat.
string.Concat
Detail The correct statements use addition in an expression before calling ToString.
And The plus operator is just an addition. The results make sense (1235 and 1236).
using System; class Program { static void Main() { string value = "1234"; int number = int.Parse(value); string value2 = number.ToString() + 1; // WRONG string value3 = number.ToString() + 2; // WRONG Console.WriteLine(value2); Console.WriteLine(value3); value2 = (number + 1).ToString(); // CORRECT value3 = (number + 2).ToString(); // CORRECT Console.WriteLine(value2); Console.WriteLine(value3); } }
12341 12342 1235 1236
Plus operator. In the C# language, the plus operator can be overloaded. Plus can mean different actions in a string expression or a numeric one.
So Adding one to a string will append the string representation of the value 1. Meanwhile adding one to a number will increment it.
Operator
To understand an operator does, we must know the types of the operands (such as strings, chars, or ints). We can use parentheses around an expression before invoking ToString.
ToString
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2023 Sam Allen.