How to Read Sequence of Numbers in C++
In this commodity, we await at escaping characters in C# strings. But what is escaping, you lot may wonder? That'south how we write special characters or characters that would otherwise be impossible to include in a string, similar "
.
This commodity is role of a learn programming series where yous need no prior noesis of programming. If you want to learn how to programme and want to larn it using .NET/C#, this is the right identify. I advise reading the whole serial in lodge, starting with Creating your first .Net/C# program, but that's not mandatory.
This commodity is part of a sub-series, starting with Introduction to string concatenation. It is not mandatory to read all articles in society, but I strongly recommend information technology, particularly if you are a beginner. If y'all are already reading the whole series in order, please discard this word of advice.
Escaping characters
As mentioned in the introduction, the action of escaping characters means yous write an "escape sequence" to represent specific characters. An escape sequence starts with a \
. It is followed past a character or a series of numbers representing the Unicode graphic symbol code.
Here are a few examples:
using System ; var quotes = "Wrap \"a few words\" with quotes." ; var newLine = "Add together a\nnew line." ; var tab = "\tAdd a tab at the begining of the string." ; var due east = "This is the letter e: \u0065" ; Panel . WriteLine ( quotes ); Panel . WriteLine ( newLine ); Console . WriteLine ( tab ); Panel . WriteLine ( e );
When nosotros run the previous lawmaking, we obtain the post-obit result:
If we take a closer wait:
- Nosotros tin can write
\"
to insert a"
grapheme inside a string, which would be incommunicable otherwise. - Nosotros can use the special
\north
to insert a new line (see below for more than special characters). - We can utilise the special
\t
to insert a horizontal tab (run into below for more special characters). - We tin use the Unicode representation of a character, prefixed past
\u
, to insert that grapheme into a string (UTF-16 or UTF-32).
In my opinion, the most helpful special characters are:
Escape sequence | Character name | Example |
---|---|---|
\' | Unmarried quote | Not related to string but to char , like var q = '\''; (non covered all the same). |
\" | Double quote | Run across preceding example. |
\\ | Backslash | var s = "c:\\folder\\some-file.ext"; |
\n | New line | See preceding example. |
\r | Carriage return | Read the Os specific line interruption section |
\t | Horizontal tab | Encounter preceding example. |
\u0000 | Unicode escape sequence (UTF-16) | To write the character e : \u0065 |
\U00000000 | Unicode escape sequence (UTF-32) | To write the character eastward : \U00000065 |
\x0[0][0][0] | Unicode escape sequence (UTF-xvi) with variable length | To write the graphic symbol e : \x65 |
See String Escape Sequences for some more characters.
Adjacent, we explore line break.
Platforms-specific line pause
In example you did not know, Windows line breaks are different from Unix-based platforms. Windows uses a sequence of both wagon render and new line (\r\n
) while Unix uses only a new line (\n
). Windows is pretty forgiving and will well-nigh probable sympathise \north
. Nevertheless, in a cantankerous-platform app targeting both Windows and Unix (due east.g., Linux and Mac), exercise you lot actually want to leave line breaks to chance? To save the day, we can use the Environment.NewLine
property instead, which adapts to the current OS.
Here is an example (same output as the newLine
variable of the preceding example):
using Organisation ; Console . WriteLine ( $"Add a { Surround . NewLine } new line." ); // We leveraged interpolation here
If nosotros take many line breaks, this can become tedious. Hopefully, nosotros can simplify this by leveraging the cord.Format
method we cover side by side.
string.Format
We tin can employ the cord.Format
method to format a cord. It is similar to interpolation, merely instead of inserting the variables straight, we need to define numerical tokens, like {0}
, {one}
, {2}
, then forth. Then, nosotros pass arguments that match those tokens in the right guild to become the last result.
Many other .NET methods allow such a construct, including Panel.WriteLine
. Here is an instance of both string.Format
and Console.WriteLine
:
using Arrangement ; var newLine = string . Format ( "Add a{0}new line." , Environment . NewLine ); Console . WriteLine ( newLine ); Console . WriteLine ( "Add together a{0}new line." , Environment . NewLine );
When running the code, both Panel.WriteLine
output the same result. The advantage hither is writing {0}
every fourth dimension we need a line break. Of course, nosotros could use interpolation with {Environment.NewLine}
straight, only it makes the string longer. Even worst, we could use concatenation like "Add together a" + Environment.NewLine + "new line."
; I find this to be the hardest lawmaking to read, making the string even longer.
But how does that work? In the background, the framework replaces the numerical tokens with the specified arguments.
There are more than to cord.Format
, including the possibility to format your values, but that's getting more and more out of the telescopic of our main subject. Next, we look at escaping characters in interpolated strings.
Interpolation-specific escaping
In an interpolated cord, nosotros utilize the characters {
and }
to wrap the chemical element to insert, like a variable. What if we want to write those characters? Information technology is as easy equally doubling them. For {
, we write {{
. For }
, we write }}
.
Hither is an example:
var name = "Darth Vader" ; var greetings = $" {{ Hi { name }}} " ; Console . WriteLine ( greetings );
As simple as that, the preceding code will output {Hello Darth Vader}
. Side by side, let'south have a look at the verbatim identifier (a.k.a. multiline strings).
The verbatim identifier
The verbatim identifier (@
) allows us to write multiline strings, but information technology'south not all. It also disables the escaping of characters, which can exist very handy when writing file paths (amongst other things). In other words, a backslash is but a backslash, not a special character that starts an escape sequence. For example, it is more convenient to write var path = @"c:\binder\some-file.ext";
than var path = "c:\\folder\\some-file.ext";
(simple vs double backslash).
Since \[character]
does not work, how tin nosotros escape "
? Similar with interpolation, nosotros just have to double it, like var v = @"Some ""quoted words"" here.";
The verbatim identifier can also be used to escape reserved keywords, similar if
, for
, public
, etc. For example, if you'd similar to create a variable named public
, you can't write var public = "some value";
because this won't compile. Even so, you could prefix your variable name with @
to make information technology work, like this: var @public = "some value";
. Using this makes your code a little harder to read, but that's a fob that can come in very handy sometimes.
More info: one identify where it was handy was to create
form
attributes in an erstwhile ASP.Internet MVC version becauseform
is a reserved keyword: we had to escape information technology using the verbatim identifier.
Reference: if y'all want to know more about reserved keywords, please visit the C# Keywords folio in the official documentation.
Next, information technology's your turn to try it out.
Exercise
In this exercise, you volition write a program that writes code. The lawmaking to write is the content of the Programme.cs
file generated by the dotnet new console
template. We include all the more or less useful plumbing that we removed in the first article of the series. Why? Well, y'all will have to write unlike tokens, escape characters, and be artistic to generate that. Writing code in code can be more challenging than it looks.
To make information technology a little more complicated, you must enquire the user to enter its first and last name, which you will have to embed in the generated code. Here is the expected result (animated sequence):
The textual output was:
using System ; class Practice { public static void Primary () { var firstName = "Carl-Hugo" ; var lastName = "Marcotte" ; Panel . WriteLine (); Console . WriteLine ( "Hello {0} {1}" , firstName , lastName ); } }
The spacing at the beginning of the lines (indentation) must be tabs, non spaces, like this:
As a side notation, I usually indent my lawmaking using spaces considering that's what Visual Studio and VS Code practise by default. I hit tab, and it gets converted to the configured number of spaces; very convenient. For the sake of this exercise, I wanted to add together a little complexity, and so I piked the tab character. Since yous are most probable very new to programming, you may not know that for some people, indenting using spaces or tabs is vital; war-like important
.
Now, to your keyboard!
Here are a few optional hints in example you feel stuck:
Hint one
Yous can use $@"..."
to combine both interpolation and multiline string merely beware the tab characters volition be harder to fit in. You lot tin can use other techniques too and fifty-fifty combine them.
Hint 2
In a multiline string, doubling the character escapes them. Otherwise, the \
character tin can escape special characters or create tabs and line breaks.
Once you lot are washed, y'all can compare with My Solution
below.
My Solution
Plan.cs
using Organization ; Console . Title = "IntroToDotNet" ; Console . Write ( "What is your commencement name? " ); var firstName = Console . ReadLine (); Panel . Clear (); Console . Write ( "What is your final proper noun? " ); var lastName = Console . ReadLine (); Panel . Clear (); var tab = "\t" ; var solution = $@"using System; class Do {{ { tab } public static void Main () { tab }{{ { tab }{ tab } var firstName = "" { firstName } "" ; { tab }{ tab } var lastName = "" { lastName } "" ; { tab }{ tab } Console . WriteLine ( "" Hello {{ 0 }} {{ i }} "" , firstName , lastName ); { tab }}} }} " ; Console . WriteLine ( solution );
Another culling would have been to only use interpolation, which results in this very long line:
var solution = $"using System;\n\nclass Exercise\n {{ \ north \ tpublic static void Main () \ northward \ t {{ \ n \ t \ tvar firstName = \ "{firstName}\";\n\t\tvar lastName = \"{lastName}\";\n\t\tConsole.WriteLine(\"Hi {{0}} {{i}}\", firstName, lastName);\n\t}}\north}}" ;
You could have used and then many combinations that I tin't list them all here. If y'all succeeded, that's what is important; no matter how you did it.
Proficient chore! You completed some other small chapter of your programming journey.
Decision
In this article, we explored the cord blazon a niggling more. We discovered that the backslash graphic symbol (\
) is used to escape characters or to create special characters like tabs (\t
) and line breaks (\r
and \north
). We then learned about the Environment.NewLine
belongings that gives us the correct platforms-specific line break. We also peaked at string.Format
to format strings using numerical tokens instead of interpolation.
Afterward, we explored some border cases to escape {
and }
in interpolated strings and "
in multiline strings. The solution was to double the characters; a.1000.a. write ""
to obtain "
. We saw that in @"..."
strings, the escape character (\
) does not work, which is an advantage that can get a disadvantage. We finally learned to utilize the verbatim identifier (@
) to bypass the reserved keywords limitation and use it as an escape grapheme for identifiers.
All in all, that'due south a lot of new content that concludes our introduction to strings mini-sub-series.
Next step
It is now fourth dimension to move to the next article: Introduction to Boolean algebra and logical operators.
Table of content
Now that you are washed with this commodity, please wait at the series' content.
Articles in this serial |
---|
Creating your get-go .Cyberspace/C# program In this commodity, nosotros are creating a pocket-sized panel awarding using the .Net CLI to get started with .Cyberspace five+ and C#. |
Introduction to C# variables In this commodity, we explore variables. What they are, how to create them, and how to use them. Variables are essential elements of a plan, making it dynamic. |
Introduction to C# constants In this commodity, we explore constants. A abiding is a special kind of variable. |
Introduction to C# comments In this article, we explore single-line and multiline comments. |
How to read user inputs from a console In this commodity, we explore how to retrieve simple user inputs from the console. This will help u.s. brand our programs more than dynamic by interacting with the user. |
Introduction to string concatenation In this commodity, we dig deeper into strings and explore cord concatenation. |
Introduction to string interpolation In this article, we explore string interpolation as another mode to compose a cord. |
Escaping characters in C# strings Y'all are here In this article, nosotros explore how to escape characters like quotes and how to write special character like tabs and new lines. |
Introduction to Boolean algebra and logical operators This article introduces the mathematical branch of algebra that evaluates the value of a condition to true or false. |
Using if-else option statements to write provisional code blocks In this commodity, we explore how to write conditional code using Boolean algebra. |
Using the switch selection statement to simplify conditional statements blocks In this commodity, we explore how to simplify certain conditional blocks by introducing the switch statement. |
Boolean algebra laws This article explores multiple Boolean algebra laws in a developer-oriented style, leaving the mathematic notation aside. |
More to come Most likely in Q1 of 2022 |
smithsciusurturs1943.blogspot.com
Source: https://www.forevolve.com/en/articles/2021/04/18/learn-coding-with-dot-net-core-part-8/
Post a Comment for "How to Read Sequence of Numbers in C++"