String Literals
String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
Here are some examples of String Literals −
Hello, World" "Welcome, \
The following is an example showing the usage of string literals −
Example
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
// string
string str1 ="Hello, World";
Console.WriteLine(str1);
// Multi-line string
string str2 = @"Welcome,
Hope you are doing great!";
Console.WriteLine(str2);
}
}
}String Object
Create string object using one of the following methods −
- By assigning a string literal to a String variable
- By using a String class constructor
- By using the string concatenation operator (+)
- By retrieving a property or calling a method that returns a string
- By calling a formatting method to convert a value or an object to its string representation
The following is how you can create a string object and compare two strings −
Example
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str1 = "John";
string str2 = "Andy";
if (String.Compare(str1, str2) == 0) {
Console.WriteLine(str1 + " and " + str2 + " are equal strings.");
} else {
Console.WriteLine(str1 + " and " + str2 + " are not equal strings.");
}
Console.ReadKey() ;
}
}
}