String in C#
String is a keyword that is use to represent a sequential collection of
characters that is called a text and the string is an object of System.String type.
We use string keyword to create string variables to hold the particular text which is a sequential collection of characters.
The string variables can hold any kind of text and by using Length property we can know the number of characters the string variable is holding.
Declaration and Initialization of string variable in C#
// Declare without initializing.
string str1;
// Declaring
and Initializing
string str2 = "Welcome to the world of
Csharp Naija";
String str3 = "Hello World!";
// Initialize
an empty string.
string str4 = String.Empty;
// Initialize
to null.
String str5 = null;
// Creating a
string from char
char[] letters = { 'a', 'b', 'c' };
string str6 = new string(letters);
If we take a closer
look at the above code snippet, we will found out that we created a string variables using string and String keywords with or without initializing a values.
Differences between string vs String in C#
From the above string declarations code
snippets, we used two keywords called string and String
to declare string variables. In C#, the string keyword is
just an alias for String so both string and String are equivalent, and you can
use whichever the naming convention you prefer to define string variables.
String Immutability
In C#, string is immutable, that is, the string object
cannot be modified once it is created. If any changes made to the string object
like add or modify an existing value, then it will simply discard the old
instance in memory and create a new instance to hold the new value.
For example, when we create a new string variable “message” with text “Welcome”, then a new instance will be
created on heap memory to hold this value. Now, if we make any changes to message variable like changing the
text from “welcome” to “welcome to Csharp naija”, then the old
instance on heap memory will be discarded and another instance will be created
on heap memory to hold the variable value instead of modifying the old instance
in the memory.
If we perform
modifications like inserting, concatenating, removing or replacing a value of
existing string multiple times, then every time the new instance will be created
on heap memory to hold the new value thereby affecting the performance of the
application automatically.
String Literals (Regular/Verbatim) in C#
String literal is a sequence of characters that
are enclosed in double quotation marks (" "). We have two kind of string
literals available in C#, these are regular and verbatim.
The regular literals
are useful when we want to embed escape characters like \n, \t, \', \",
etc. in C#.
String Literals (Regular)
Following is an example of using regular string literals to embed
escape characters in C#.
string names = "Musa\nSule\nGadabs";
Console.WriteLine(names);
/*
Output:
Musa
Sule
Gadabs
*/
string msg = "Welcome to
\"Csharpnaija\" world";
Console.WriteLine(msg);
// Output: Welcome to
"Csharpnaija" world
String Literals (Verbatim)
The special character @
will serve as verbatim literal and it is use to
represent a multiline string or a string with backslash characters, for example
to represent file paths.
Following is an example of using verbatim literal @
in C# to represent a
multiline string and a file path.
string path = @"C:\Users\Csharp
naija\Documents\";
Console.WriteLine(path);
//Output:
C:\Users\Csharp naija\Documents\
string msg = @"Hi Guys,
Welcome to Csharp naija World
Learning Made Easy";
Console.WriteLine(msg);
/* Output:
Hi Guest,
Welcome to Csharp naija
World
Learning Made Easy
*/
string msg1 = @"My wife's name is
""Sakinat.""";
Console.WriteLine(msg1);
Format Strings in C#
The format string is a string whose
contents can be determined dynamically at runtime. We can create a format
string by using the Format method
and embedding placeholders in braces that will be replaced by other values at
runtime.
Following is the example of using a format string to determine
the string content dynamically at runtime.
string name = "Musa Sule";
string location = "Abuja, Nigeria";
string user = string.Format($"Name: {name}, Location: {location}");
Console.WriteLine(user);
// Output: Name: Musa Sule,
Location: Abuja, Nigeria
C# Access Individual Characters from Strings
We can access individual characters of a
string by using array notation with index values as shown in the
example below.
string name = "Musa Sule Gadabs";
for (int i = 0;
i < name.Length; i++)
{
Console.Write(name[i]);
}
// Output: Musa Sule Gadabs
C# String Properties
The following table lists the available
string properties in C#.
Property |
Description |
Chars |
It
helps us to get the characters from the current string object based on the
specified position. |
Length |
It
returns the number of characters in the current String object. |
C# String Methods
The string class contains various methods to
manipulate string objects.
The following table lists important string methods
available in C# programming language.
Method |
Description |
Clone() |
It
returns a reference to this instance of String. |
Compare(String, String) |
It
compares two specified String objects and returns an integer that indicates
their relative position in the sort order. |
Concat(String,
String) |
It
concatenates two specified instances of String. |
Contains(String) |
It
returns a value indicating whether a specified substring occurs within this
string. |
Copy(String) |
It
creates a new instance of String with the same value as a specified String. |
Format(String,
Object) |
It
replaces one or more format items in a specified string with the string
representation of a specified object |
Trim() |
It
removes all leading and trailing white-space characters from the current
String object. |
ToLower() |
It
converts a given string to lowercase. |
ToUpper() |
It
converts a given string to uppercase. |
Split(Char[]) |
It
splits a string into substrings that are based on the characters in an array. |
Substring(Int32) |
It
retrieves a substring from this instance. The substring starts at a specified
character position and continues to the end of the string. |
IndexOf(String,
Int32, Int32) |
Reports
the zero-based index of the first occurrence of the specified string in this
instance. The search starts at a specified character position and examines a
specified number of character positions. |
This is how we can use
strings in our applications to hold the required text in C#.
Thank you
References
1.
Tutlane
Comments
Post a Comment