Unit -4 String in C#
A string is an object of type String whose value is text. Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes: There's no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0'). The Length property of a string represents the number of Char objects it contains.
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "Programing";
// print string
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadLine();
}
}
}
Creating a String Object
We can use the string keyword to declare a string variable. The string keyword is an alias for the System.String class. We 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
Example
using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
// --- 1. STRING LITERAL AND CONCATENATION ---
string fname, lname; // Declare two string variables
fname = "Rowan"; // Assign first name
lname = "Atkinson"; // Assign last name
// Create a character array
char[] letters = { 'H', 'e', 'l', 'l', 'o' };
// Create a string array
string[] sarray = { "Hello", "From", "Class", "12" };
// Concatenate (join) two strings using + operator
string fullname = fname + " " + lname; // Added space between names
Console.WriteLine("Full Name: " + fullname);
// --- 2. USING STRING CONSTRUCTOR ---
// Convert character array to string
string greetings = new string(letters);
Console.WriteLine("Greetings: " + greetings);
// --- 3. USING STRING.JOIN() METHOD ---
// Join all elements of string array with a space between them
string message = String.Join(" ", sarray);
Console.WriteLine("Message: " + message);
// --- 4. USING STRING.FORMAT() METHOD
// Create a DateTime object
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
// Format string to include time and date
string chat = ("Message sent at " + waiting.ToString("t") + " on " + waiting.ToString("D"));
Console.WriteLine("Message: " + chat);
}
}
}
C# String Methods and Operations
In C#, a string is
a sequence of characters enclosed in double quotes (" ").
Example:
string name = "Ramesh";A string in C# is actually an object
of the System.String
class.
That means it has properties (like Length)
and methods (like Concat(), Replace(),
etc.)
to perform different operations on text.
1. Get the Length of a String
We can find the total number of
characters (including spaces) in a string using the Length
property.
Example:
using System; namespace CsharpString { class Test { public static void Main(string [] args) { string str = "C# Programming"; Console.WriteLine("String: " + str); int length = str.Length; Console.WriteLine("Length: " + length); } } }Output:
String: C# ProgrammingLength: 14 2. Join Two Strings (Concat)
We can join two or more strings
using the Concat()
method or the +
operator.
Example:
using System; namespace CsharpString { class Test { public static void Main(string [] args) { string str1 = "C# "; string str2 = "Programming"; // Using Concat() string joinedString = string.Concat(str1, str2); Console.WriteLine("Joined string: " + joinedString); // Using + operator string name = str1 + str2; Console.WriteLine("Joined using + : " + name); } } }Output:
Joined string: C# ProgrammingJoined using + : C# Programming 3. Compare Two Strings (Equals)
The Equals()
method checks whether two strings have the same content or not.
It returns true
if both strings are equal; otherwise, false.
Example:
using System; namespace CsharpString { class Test { public static void Main(string [] args) { string str1 = "C# Programming"; string str2 = "C# Programming"; string str3 = "Program"; Console.WriteLine("str1 and str2 are equal: " + str1.Equals(str2)); Console.WriteLine("str1 and str3 are equal: " + str1.Equals(str3)); } } }Output:
str1 and str2 are equal: Truestr1 and str3 are equal: False 4. Convert Case of a String (Uppercase / Lowercase)
You can change the text to uppercase
using ToUpper()
and to lowercase using ToLower().
Example:
using System; namespace MyApplication { class Program { static void Main(string[] args) { string txt = "Hello World"; Console.WriteLine(txt.ToUpper()); // HELLO WORLD Console.WriteLine(txt.ToLower()); // hello world } }}Output:
HELLO WORLDhello world 5. Clone()
The Clone()
method returns a reference (copy) of the existing string object.
Example:
string str = "C#";string str2 = (string)str.Clone();Console.WriteLine(str2); // Output: C#Note: It does not create a completely new copy in memory — it just returns the same reference.
6. Contains()
Checks whether a substring exists
within a string.
It returns true if found; otherwise, false.
Example:
string sentence = "Welcome to C# class";Console.WriteLine(sentence.Contains("C#")); // TrueConsole.WriteLine(sentence.Contains("Java")); // False
7. Copy()
Creates a new string object with the same value as another string.
Example:
string str1 = "Hello";string str2 = string.Copy(str1);Console.WriteLine(str2); // Hello Note: Copy() is now outdated
(deprecated). Use String.Clone()
or new
string(str1.ToCharArray()) instead.
8. IndexOf()
Returns the index position (starting from 0) of the first occurrence of a character or substring.
Example:
string str = "Programming";Console.WriteLine(str.IndexOf("g")); // 3Console.WriteLine(str.IndexOf("mm")); // 69. Insert()
Inserts a substring at the specified index position.
Example:
string str = "C# Language";string result = str.Insert(3, "Programming ");Console.WriteLine(result);Output:
C# Programming Language
10. Replace()
Replaces specified characters or substrings with another value.
Example:
string text = "Welcome to Tutorials Point";string newText = text.Replace("Tutorials Point", "Class 12");Console.WriteLine(newText);Output:
Welcome to Class 1211. Substring()
Extracts a portion of the string starting from a specific index.
Example:
string str = "C# Programming";string sub = str.Substring(3, 11);Console.WriteLine(sub);Output:
Programming 12. Trim()
Removes extra spaces from the beginning and end of a string.
Example:
string str = " Hello World ";Console.WriteLine("Before Trim: '" + str + "'");Console.WriteLine("After Trim: '" + str.Trim() + "'");Output:
Before Trim: ' Hello World 'After Trim: 'Hello World'
String Functions
Functions are static methods of the String class that can be called directly
using the class name, without creating or using a string object.
These usually take strings as parameters and return
a new string or value.
Syntax:
String.FunctionName(arguments);
Examples and Explanation:
Function
Description
Example
String.Concat(str1,
str2)
Combines two or more strings.
String.Concat("C#",
" Rocks") → "C#
Rocks"
String.Compare(str1,
str2)
Compares two strings (case-sensitive).
String.Compare("a",
"A") → 1
String.Copy(str)
Creates a copy of a string.
String.Copy("Hello")
→ "Hello"
String.Format()
Formats a string using placeholders.
String.Format("Name:
{0}", "Dinesh") → "Name: Dinesh"
String.Join(separator,
array)
Joins elements of an array into a single string.
String.Join("-",
new string[]{"A","B","C"}) → "A-B-C"
String.IsNullOrEmpty(str)
Checks if a string is null or empty.
String.IsNullOrEmpty("")
→ True
String.IsNullOrWhiteSpace(str)
Checks if a string is null or whitespace.
String.IsNullOrWhiteSpace("
") → True
Example Code:
using System;class Program { static void Main() { string[] words = { "I", "Love", "C#" }; Console.WriteLine(String.Concat("Hello", " World")); Console.WriteLine(String.Join(" ", words)); Console.WriteLine(String.Compare("apple", "banana")); Console.WriteLine(String.IsNullOrEmpty("")); Console.WriteLine(String.Format("Name: {0}, Age: {1}, Address: {3}, Grade: {2}", "Ram", 20, "XI" ,"Butwal Golpark")); }}1. Write a C# program to:
Ask the user to enter an email address.
Check whether the email contains '@' and '.'.
Extract and display the domain name.
(Hint: use Contains(), IndexOf(), Substring())
2. Write a C# program that:
Creates a string array of three hobbies (e.g., "Reading", "Coding", "Music").
Joins them into a single string using String.Join() with a comma and space.
Displays the result as:
My hobbies are: Reading, Coding, Music
3. Write a program that:
Takes a sentence like "Knowledge is power".
Replaces "power" with "everything".
Converts it to uppercase and prints:
KNOWLEDGE IS EVERYTHING
Comments
Post a Comment