0% found this document useful (0 votes)
34 views22 pages

Str Processing

Uploaded by

Shiva Dhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views22 pages

Str Processing

Uploaded by

Shiva Dhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Strings and Text Processing in C#

1. What is String?
2. Creating and Using Strings
◦ Declaring, Creating, Reading and Printing
3. Manipulating Strings
◦ Comparing, Concatenating, Searching, Extracting Substrings,
Splitting
4. Other String Operations
◦ Replacing Substrings, Deleting Substrings, Changing Character
Casing, Trimming
What Is String?
◦ Strings are sequences of characters
◦ Each character is a Unicode symbol
◦ Represented by the string data type in C# (System.String)
◦ Example:
string s = "Hello, C#";

s H e l l o , C #
The System.String Class
◦ Strings are represented by System.String objects in .NET
Framework
◦ String objects contain an immutable (read-only) sequence
of characters
◦ Strings use Unicode in to support multiple languages and
alphabets
◦ System.String is of reference type
Immutable
◦ String objects are immutable: they cannot be changed after
they have been created.
◦ All of the String methods and C# operators that appear to
modify a string actually return the results in a new string
object.
string s1 = "Hello ";
string s2 = s1;
s1 += "World";

System.Console.WriteLine(s2);
//Output: Hello
The System.String Class
◦String objects are like arrays of characters (char[])
◦Have fixed length (String.Length)
◦Elements can be accessed directly by index
◦ The index is in the range [0...Length-1]
string s = "Hello!";
int len = s.Length; // len = 6
char ch = s[1]; // ch = 'e'

index = 0 1 2 3 4 5
s[index] = H e l l o !
Declaring Strings
◦There are two ways of declaring string variables:
◦Using the C# keyword string
◦Using the .NET's fully qualified class name System.String
◦The following three declarations are equivalent

string str1;
System.String str2;
String str3;
Creating Strings
◦ Before initializing a string variable has null value

◦ Strings can be initialized by:

◦ Assigning a string literal to the string variable

◦ Assigning the value of another string variable

◦ Assigning the result of operation of type string


Creating Strings
◦ Not initialized variables has value of null
string s; // s is equal to null

◦ Assigning a string literal


string s = "I am a string literal!";

◦ Assigning from another string variable


string s2 = s;

◦ Assigning from the result of string operation


string s = 42.ToString();
Reading and Printing Strings
◦ Reading strings from the console
◦ Use the method Console.ReadLine()

string s = Console.ReadLine();

Printing strings to the console


Use the methods Write() and WriteLine()
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);
Console.WriteLine("Welcome to our party!");
Comparing Strings
◦ A number of ways exist to compare two strings:
◦ Dictionary-based string comparison
◦ Case-insensitive
int result = string.Compare(str1, str2, true);
// result == 0 if str1 equals str2
// result < 0 if str1 if before str2
// result > 0 if str1 if after str2

◦ Case-sensitive

string.Compare(str1, str2, false);


Comparing Strings
◦ Equality checking by operator ==
◦ Performs case-sensitive compare
if (str1 == str2)
{

}

◦ Using the case-sensitive Equals() method


◦ Same effect like the operator ==
if (str1.Equals(str2))
{

}
Concatenating Strings
◦ There are two ways to combine strings:
◦ Using the Concat() method
string str = String.Concat(str1, str2);
◦ Using the + or the += operators
string str = str1 + str2 + str3;
string str += str1;

◦ Any object can be appended to string


string name = "Peter";
int age = 22;
string s = name + " " + age; //  "Peter 22"
Searching in Strings
◦ Finding a character or substring within given string
◦ First occurrence
IndexOf(string str)

◦ First occurrence starting at given position


IndexOf(string str, int startIndex)

◦ Last occurrence
LastIndexOf(string)
Searching in Strings – Example
string str = "C# Programming Course";
int index = str.IndexOf("C#"); // index = 0
index = str.IndexOf("Course"); // index = 15
index = str.IndexOf("COURSE"); // index = -1
// IndexOf is case-sensetive. -1 means not found
index = str.IndexOf("ram"); // index = 7
index = str.IndexOf("r"); // index = 4
index = str.IndexOf("r", 5); // index = 7
index = str.IndexOf("r", 8); // index = 18

index = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 …
s[index] = C # P r o g r a m m i n g …
Extracting Substrings
◦ str.Substring(int startIndex, int length)
string filename = @"C:\Pics\fall2020.jpg";
string name = filename.Substring(8, 8);
// name is fall2020

◦ str.Substring(int startIndex)
string filename = @"C:\Pics\fall2020.jpg";
string nameAndExtension = filename.Substring(8);
// nameAndExtension is fall2020.jpg

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

C : \ P i c s \ f a l l 2 0 2 0 . j p g
Splitting Strings
◦ To split a string by given separator(s) use the following method:
string[] Split(params char[])

◦ Example:
string listOfGames = “BattleField, Uncharted, COD, NFS”;
string[] games = listOfGames.Split(' ', ',' , '.');
Console.WriteLine("Available games are:");
foreach (string game in games)
{
Console.WriteLine(game);
}
Replacing and Deleting Substrings
◦ Replace(string, string) – replaces all occurrences of given string
with another
◦ The result is new string (strings are immutable)
string course = “MCA + MBA + MSC”;
string replaced = courses.Replace("+", "and");
// MCA and MBA and MSC

◦ Remove(index, length) – deletes part of a string and produces


new string as result
string price = "$ 1234567";
string lowPrice = price.Remove(2, 3);
// $ 4567
Changing Character Casing
◦ Using method ToLower()
string alpha = "aBcDeFg";
string lowerAlpha = alpha.ToLower(); // abcdefg
Console.WriteLine(lowerAlpha);

◦ Using method ToUpper()


string alpha = "aBcDeFg";
string upperAlpha = alpha.ToUpper(); // ABCDEFG
Console.WriteLine(upperAlpha);
Trimming White Space
◦ Using method Trim()
string s = " example of white space ";
string clean = s.Trim();
Console.WriteLine(clean);

◦ Using method Trim(chars)


string s = " \t\nHello!!! \n";
string clean = s.Trim(' ', ',' ,'!', '\n','\t');
Console.WriteLine(clean); // Hello

◦ Using TrimStart() and TrimEnd()


string s = " C# ";
string clean = s.TrimStart(); // clean = "C# "
Method ToString()
◦ All classes have public virtual method ToString()
◦ Returns a human-readable, culture-sensitive string representing the object

◦ Most .NET Framework types have own implementation of ToString()


◦ int, float, bool, DateTime

int number = 5;
string s = "The number is " + number.ToString();
Console.WriteLine(s); // The number is 5
Sample Programs
1. Write a program which
Takes an Input String
Appends a digit after every character with total count of that
character (case is ignored) in the string.
Example if input is Banana, the output must be B1a3n2a3n2a3
Sample Programs
1. Write a program which
Removes all characters from the second string which is there in
the first string
Enter String 1: programming
Enter String 2: computer
On removing characters from second we get : cute

You might also like