Algorithm
In C#, a string
is a sequence of characters that represents text. It is one of the built-in data types in C# and is part of the .NET Framework. Here are some key points about C# strings:
Code Examples
#1 Example- Create string in C# Program
Code -
C# Programming
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "DevsEnv";
// print string
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
DevsEnv
#2 Get the Length of a string in C# Program
Code -
C# Programming
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);
// get length of str
int length = str.Length;
Console.WriteLine("Length: "+ length);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
Length: 14
#3 Join two strings in C# Programming
Code -
C# Programming
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);
// create string
string str2 = "Programming";
Console.WriteLine("string str2: " + str2);
// join two strings
string joinedString = string.Concat(str1, str2);
Console.WriteLine("Joined string: " + joinedString);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
string str2: Programming
Joined string: C# Programming
#4 compare two strings in C# program
Code -
C# Programming
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "DevsEnv";
// compare str1 and str2
Boolean result1 = str1.Equals(str2);
Console.WriteLine("string str1 and str2 are equal: " + result1);
//compare str1 and str3
Boolean result2 = str1.Equals(str3);
Console.WriteLine("string str1 and str3 are equal: " + result2);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
string str1 and str3 are equal: False
#5 String interpolation in C# Programming
Code -
C# Programming
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string name = "DevsEnv";
// string interpolation
string message = $"Welcome to {name}";
Console.WriteLine(message);
Console.ReadLine();
}
}
}
Copy The Code &
Try With Live Editor
Output
Demonstration
C# Programming Examples - String Examples