Methods and Text Manipulation
Techniques in C#
By: Jihad A.Qadir
Lecturer at Raparin University and Erbil polytechnic university // Computer Science Department
Methods
A method is a group of statements that together perform a task. Every C# program
has at least one class with a method named Main.
To use a method, you need to:
Define the method
Ex:
public int FindMax(int num1, int num2)
{
…..
}
Call the method
Ex:
FindMax(2,4);
Why to Use Methods?
More manageable programming
Split large problems into small pieces
Better organization of the program
Improve code readability
Improve code understandability
Avoiding repeating code
Improve code maintainability
Code reusability
Using existing methods several times
3
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The syntax for
defining a method in C# is as follows:
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
• Access Specifier: This determines the visibility of a variable or a method from another class.
• Return type: A method may return a value. The return type is the data type of the value the method
returns. If the method is not returning any values, then the return type is void.
• Method name: Method name is a unique identifier and it is case sensitive.
• Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from
a method. The parameter list refers to the type, order, and number of the parameters of a method.
• Method body: This contains the set of instructions needed to complete the required activity.
Defining Methods in C#- Example
Following code snippet shows a function FindMax
It takes two integer values and returns the larger of the two.
It has public access specifier, so it can be accessed from outside the class using an instance of the class.
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
Calling Methods in C#
You can call a method using the name of the method. The following example illustrates this:
using System; static void Main(string[] args)
namespace CalculatorApplication {
{ /* local variable definition */
class NumberManipulator int a = 100;
{ int b = 200;
public int FindMax(int num1, int num2) int ret;
{ NumberManipulator n = new NumberManipulator();
/* local variable declaration */
int result; //calling the FindMax method
ret = n.FindMax(a, b);
if (num1 > num2) Console.WriteLine("Max value is : {0}", ret );
result = num1; Console.ReadLine();
else }
result = num2; }
return result; }
}
Output is: Max value is : 200
Math Class Methods
Math class methods allow the programmer to perform certain common mathematical calculations.
We use various Math class methods to introduce the concept of methods in general.
Some examples of Math methods that contains in the Framework Class Library.
Method Description Example
Ceiling( x ) rounds x to the smallest integer not less than x Ceiling( 9.2 ) is 10.0 , Ceiling( -9.8 ) is -9.0
Exp( x ) exponential method ex Exp( 1.0 ) is approximately = 2.71828182845
Exp( 2.0 ) is approximately = 7.38905609893
Floor( x ) rounds x to the largest integer not greater than x Floor( 9.2 ) is 9.0 , Floor( -9.8 ) is -10.0
Max( x, y ) larger value of x and y (also has versions for Max( 2.3, 12.7 ) is 12.7 , Max( -2.3, -12.7 ) is
float, int and long values) -2.3
Min( x, y ) smaller value of x and y (also has versions for Min( 2.3, 12.7 ) is 2.3 , Min( -2.3, -12.7 ) is -
float, int and long values) 12.7
Pow( x, y ) x raised to power y (xy) Pow( 2.0, 7.0 ) is 128.0 , Pow( 9.0, 0.5 ) is
3.0
Sqrt( x ) square root of x Sqrt( 900.0 ) is 30.0 , Sqrt( 9.0 ) is 3.0
Random-Number Generation
The Random class defined in the .NET Framework class library provides functionality to generate
random numbers.
The following code returns a random number:
int num = random.Next();
The following code returns a random number less than 1000.
int num = random.Next(1000);
The following code returns a random number between min and max:
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
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 (2)
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 !
Strings – First Example
static void Main()
{
string s =
"Stand up, stand up, Balkan Superman.";
Console.WriteLine("s = \"{0}\"", s);
Console.WriteLine("s.Length = {0}", s.Length);
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("s[{0}] = {1}", i, s[i]);
}
}
Manipulating Strings
Comparing, Concatenating, Searching, Extracting
Substrings, Splitting
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 (2)
Equality checking by operator ==
Performs case-sensitive compare
if (str1 == str2)
{
…
}
Using the case-sensitive Equals() method
The same effect like the operator ==
if (str1.Equals(str2))
{
…
}
Comparing Strings – Example
Finding the first string in a lexicographical order from a given
list of strings:
string[] towns = {"Ranya", "Hajyawa", "Dwkan", "Qaladze",
"SUlaimani", "Halanja", "Kalar"};
string firstTown = towns[0];
for (int i=1; i<towns.Length; i++)
{
string currentTown = towns[i];
if (String.Compare(currentTown, firstTown) < 0)
{
firstTown = currentTown;
}
}
Console.WriteLine("First town: {0}", firstTown);
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
Extracting substrings
str.Substring(int startIndex, int length)
string filename = @"C:\Pics\Rila2009.jpg";
string name = filename.Substring(8, 8);
// name is Rila2009
str.Substring(int startIndex)
string filename = @"C:\Pics\Summer2009.jpg";
string nameAndExtension = filename.Substring(8);
// nameAndExtension is Summer2009.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 \ R i l a 2 0 0 5 . j p g
Splitting Strings
To split a string by given separator(s) use the following
method:
string[] Split(params char[])
Example:
string listOfanimal ="ant, snake, cow, dog.";
string[] animals = listOfanimal.Split(' ', ',', '.');
Console.WriteLine("Available animals are:");
foreach (string anm in animals)
{
Console.WriteLine(anm);
}
Replacing and Deleting Substrings
Replace(string, string) – replaces all occurrences of
given string with another
The result is new string (strings are immutable)
string lang = "java + c# + C++";
string replaced = lang.Replace("+", "and");
// java and c# and C++
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);
Formatting Dates
Dates have their own formatting strings
d, dd – day (with/without leading zero)
M, MM – month
yy, yyyy – year (2 or 4 digits)
h, HH, m, mm, s, ss – hour, minute, second
DateTime now = DateTime.Now;
Console.WriteLine("Now is {0:d.MM.yyyy HH:mm:ss}", now);
// Now is 31.11.2009 11:30:32
HW:
Using random number generation to Simulate the game of Craps.
Questions?
25