Skip to main content

 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

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...

Unit 2 Java

Data Types A data type defines the kind of data a variable can store, the operations that can be performed on it, and the amount of memory allocated. Java Primitive Data Types Data Type Size Range (Approx.) Example Byte 1 byte -128 to 127 byte a = 100; short 2 bytes -32,768 to 32,767 short s = 1000; Int 4 bytes -2,147,483,648 to 2,147,483,647 int num = 50000; Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long l = 100000L; float 4 bytes ~6–7 decimal digits float f = 5.75f; double 8 bytes ~15 decimal digits double d = 19.99; Char 2 bytes Single Unicode character char c = 'A'; boolean 1 bit* tru...