CSharp – Strings
In C#, you can use strings as:
– string keyword to declare a string variable (alias for the System.String class)
– array of characters
How you can use string
using System; using System.Collections; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //from string literal and string concatenation string fname, lname; fname = "Rowan"; lname = "Atkinson"; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //by using string constructor char[] letters = { 'H', 'e', 'l', 'l', 'o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //methods returning string string[] sarray = { "Hello", "From", "Tutorials", "Point" }; 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); Console.ReadKey(); } } }
The result is:
Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
Comparing Strings
using System; using System.Collections; namespace ConsoleApplication1 { class StringProg { static void Main(string[] args) { string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal."); } Console.ReadKey(); } } }
The result is:
This is test and This is text are not equal.
Detect a string
using System; namespace ConsoleApplication1 { class StringProg { static void Main(string[] args) { string str = "This is test"; if (str.Contains("test")) { Console.WriteLine("The sequence 'test' was found."); } Console.ReadKey(); } } }
The result is:
The sequence ‘test’ was found.
Get a substring
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "Last night I dreamt of San Pedro"; Console.WriteLine(str); string substr = str.Substring(23); // from 24th character to the end Console.WriteLine(substr); } Console.ReadKey() ; } }
The result is:
San Pedro
Joining Strings
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string[] starray = new string[]{"Down the way nights are dark", "And the sun shines daily on the mountain top", "I took a trip on a sailing ship", "And when I reached Jamaica", "I made a stop"}; string str = String.Join("\n", starray); Console.WriteLine(str); } Console.ReadKey() ; } }
The result is:
Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
My website: http://www.lucedigitale.com
Ref: http://www.tutorialspoint.com/csharp/csharp_strings.htm