Skip to main content

Unit -4 String in C#(Class 12)

 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# Programming
Length: 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# Programming
Joined 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: True
str1 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 WORLD
hello 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#")); // True
Console.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"));  // 3
Console.WriteLine(str.IndexOf("mm")); // 6

 9. 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 12

 11. 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

Popular posts from this blog

Unit 2 Operating System

  Unit- 2  Process and Process Scheduling 2.1 Introduce Process, Program and Process Life Cycle  Process Process is something that is currently under execution. So, an active program can be called a Process. Examples: ●        Opening a web browser to search something on the internet — the browser becomes a process. ●        Launching a music player to enjoy your favorite tunes — the music player is also a process. In computing, a process is the instance of a computer program that is being executed by one or many threads. It contains the program code and its activity. Modern operating systems support multithreading , meaning a process can have multiple threads running concurrently .   A Process has various attributes associated with it. Some of the attributes of a Process are: ●          Process Id: Every process will be given a unique id that identifies the process...

Unit-1 Introduction to C#.NET (Class 12)

  What is .NET Framework? The .NET Framework is a software development platform developed by Microsoft. It provides tools and libraries to build and run Windows applications, web services, and web apps. It gives tools and libraries that make it easier to write programs. It also helps the computer run those programs safely and efficiently. Microsoft started working on .NET Framework in the late 1990s . The first version, .NET Framework 1.0 , was released in 2002 .   The .NET Framework is made up of several important components: 1.       Common Language Runtime (CLR) is the core engine that runs your program. It converts your code into machine code that the computer can understand, manages memory, handles errors, and ensures that your program runs safely. 2.       The Class Library is a large collection of ready-made code that helps you perform common tasks like working with files, databases, graphics, the i...

Introduction to Software Engineering (Class 12)

 Introduction to Software Engineering Software engineering is the branch of computer science that deals with the design, development, testing, and maintenance of software applications. Software engineers apply engineering principles and knowledge of programming languages to build software solutions for end users. IEEE, in its standard 610.12-1990, defines software engineering as the application of a systematic, disciplined, which is a computable approach for the development, operation, and maintenance of software. Boehm defines software engineering, which involves, ‘the practical application of scientific knowledge to the creative design and building of computer programs. It also includes associated documentation needed for developing, operating, and maintaining them.’ Importance of Software Engineering Reduces complexity Large software systems are divided into smaller, manageable modules. Each module is developed and solved independently, ...