Strings in C#
Strings in C#
In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class.
Creating a String Object
You can 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 example demonstrates this −
using System;
namespace StringApplication {
class Program {
static void Main(string[] args) {
//from string literal and string concatenation
string fname, lname;
fname = "Parth";
lname = "Jolly";
char []letters= { 'H', 'e', 'l', 'l', 'o' };
string [] sarray={ "Hello", "From", "Tutorials", "Point" };
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//by using string constructor { 'H', 'e', 'l', 'l', 'o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//methods returning string { "Hello", "From", "Strings", "Tutorial" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
Console.WriteLine("Message: {0}", chat);
}
}
}
When the above code is compiled and executed, it produces the following result −
Full Name: ParthJolly
Greetings: Hello
Message: Hello From Strings Tutorial
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
Properties of the String Class
The String class has the following two properties −
Sr.No. |
Property & Description |
1 |
Chars Gets the Char object at a specified position in the current String object. |
2 |
Length Gets the number of characters in the current String object. |
