TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Increment String That Contains a Number

Consider an issue with incrementing numbers stored as strings. Use int.Parse and ToString.
Increment string, number. Numbers are sometimes stored as strings. How can we increment these numbers? Occasionally programmers make mistakes because of how the string.Concat method works with the plus operator.
Example. The string "1234" contains a number. We can parse it with int.Parse. Next, we see problematic statements. 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

Correct: 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).

C# program that increments strings containing numbers 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); } } Output 12341 12342 1235 1236
Plus. In the C# language, the plus operator can be overloaded. Plus can mean different actions in a string expression or a numeric one. Adding one to a string will append the string representation of the value 1.

And: Adding one to a number will increment it. With the plus operator, context is important.

Operator
Summary. Operators are sometimes confusing. 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
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf