0% found this document useful (0 votes)
24 views

String & Math Functions

The document discusses various string functions and methods in C#. It provides examples of creating and initializing string objects, accessing string properties like Length and Chars, and using commonly used string methods like Compare, Concat, Copy, Split, Trim, ToCharArray, ToLower, ToUpper, PadLeft, PadRight, GetEnumerator, Replace, Clone, Contains, and EndsWith. Examples are given to demonstrate how each of these string methods works.

Uploaded by

Thanu shree
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

String & Math Functions

The document discusses various string functions and methods in C#. It provides examples of creating and initializing string objects, accessing string properties like Length and Chars, and using commonly used string methods like Compare, Concat, Copy, Split, Trim, ToCharArray, ToLower, ToUpper, PadLeft, PadRight, GetEnumerator, Replace, Clone, Contains, and EndsWith. Examples are given to demonstrate how each of these string methods works.

Uploaded by

Thanu shree
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

String Functions

 In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a
string variable.
 The string keyword is an alias for the System.String class.

Creating a String Object Examples:

string fname, lname;


fname = “John"; lname = “Abraham";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);

result is

Full Name: John Abraham


Greetings: Hello ICT Academy
Properties of the String Class:

Chars : Gets the Char object at a specified position in the current String object.
Length: Gets the number of characters in the current String object.

Methods of the String Class:

The String class has numerous methods that help you in working with the string objects. The following table
provides some of the most commonly used methods:
public static int Compare stringstrA, stringstrB

Compares two specified string objects and returns an integer that indicates their relative position in the
sort order.

public static string Concats tringstr0, stringstr1


Concatenates two string objects.

public static string Copy stringstr


Creates a new String object with the same value as the specified string.

ICT Academy
public string[] Splitchar[]separator, intcount

Returns a string array that contains the substrings in the current string object, delimited by elements of a specified

Unicode character array. The int parameter specifies the maximum number of substrings to return.

public char[] ToCharArray


Returns a Unicode character array with all the characters in the current string object.

public string Trim


Removes all leading and trailing white-space characters from the current String object.

public string ToLower


Returns a copy of this string converted to lowercase.

public string ToUpper


Returns a copy of this string converted to uppercase.
ICT Academy
public string Clone()
It is used to return a reference to this instance of String.

Public string Compare(String, String)


It is used to compares two specified String objects. It returns an integer that indicates their relative position
in the sort order.

public string Endswith(string)


It is used to check that the end of this string instance matches the specified string.

public string Equals(String, String)


It is used to determine that two specified String objects have the same value.

public static string Format (String first, Object second)


It is used to replace one or more format items in a specified string with the string representation of a specified
object.

  ICT Academy 4
public CharEnumerator GetEnumerator() 
It is used to retrieve an object that can iterate through the individual characters in this string.

public override int GetHashCode()  
This method is used to get hash code of this string. It returns an integer value.

public string GetType() 
It is used to get the Type of the current instance.

public TypeCode GetTypeCode() 
It is used to return the TypeCode for class String.

public bool IsNormalized() 
This method is used to check whether the string is in Unicode normalization form. It returns boolean
value.

ICT Academy 5
public string PadLeft(Int32 length)   

public string PadLeft(Int32, Char)   

PadLeft() method is used to get a new string that right-aligns the characters in this string if the string
length is less than the specified length.

For example, suppose you have "hello C#" as the string which has 8 length of characters and you are
passing 10 for the padleft, it shifts the string at right side after two whitespaces. It means PadLeft() method
provides padding to the string for the specified length. It is used for formatting string content.

public string PadRight(Int32 length)  

public string PadRight(Int32, Char) 
This method is used to get a new string that left-aligns the characters in this string by padding them with
spaces on the right, for a specified total length.

ICT Academy 6
Examples:
The following example demonstrates some of the methods mentioned above:
using System;
namespace StringApplication{
class StringProg{
static void Main(string[] args){
string str1 = "This is test"; string str2 = "This is text";
if (String.Compare(str1, str2) == 0){
Console.WriteLine(str1 + " and " + str2 + " are equal.");}
else{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");}
Console.ReadKey() ;}
}
}
When the above code is compiled and executed, it produces the following result:
This is test and This is text are not equal.

ICT Academy
Getting a Substring:

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
}
}
}

ICT Academy 8
PadRight() Method Example

using System;   
public class StringExample     
{    
        public static void Main(string[] args)    
        {    
           string s1 = "Hello C#";// 8 length of characters  
           string s2 = s1.PadRight(15);  
           Console.Write(s2);//padding at right side (15-8=7)  
           Console.Write("Java");//will be written after 7 white spaces  
       }    
}

ICT Academy 9
GetEnumerator() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s2 = "Hello C#"; CharEnumerator ch = s2.GetEnumerator();
while(ch.MoveNext())
{
Console.WriteLine(ch.Current);
}
}
}

ICT Academy 10
TrimEnd() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
char[] ch = {'#'};  
string s2 = s1.TrimEnd(ch);
}
}

ICT Academy 11
Replace() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#, Hello .Net, Hello Java";
string s2 = s1.Replace("Hello","Cheers");
Console.WriteLine(s2);
}
}

ICT Academy 12
C# String Clone () method example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = (String)s1.Clone();
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}

ICT Academy 13
C# String Compare() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
string s2 = "hello";
string s3 = "csharp";
string s4 = "mello";

Console.WriteLine(string.Compare(s1,s2));
Console.WriteLine(string.Compare(s2,s3));
Console.WriteLine(string.Compare(s3,s4));
}
} ICT Academy 14
C# String CompareTo() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
string s2 = "hello";
string s3 = "csharp";
Console.WriteLine(s1.CompareTo(s2));
Console.WriteLine(s2.CompareTo(s3));
}
}

ICT Academy 15
C# String Concat() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = "C#";
Console.WriteLine(string.Concat(s1,s2));
}
}

ICT Academy 16
C# String Contains() method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = "He";
string s3 = "Hi";
Console.WriteLine(s1.Contains(s2));
Console.WriteLine(s1.Contains(s3));

}
}

ICT Academy 17
C# String Copy() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello ";
string s2 = string.Copy(s1);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}

ICT Academy 18
C# String CopyTo() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#, How Are You?";
char[] ch = new char[15];
s1.CopyTo(10,ch,0,12);
Console.WriteLine(ch);
}
}

ICT Academy 19
C# String EndsWith() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello";
string s2 = "llo";
string s3 = "C#";
Console.WriteLine(s1.EndsWith(s2));
Console.WriteLine(s1.EndsWith(s3));
}
}

ICT Academy 20
C# String Equals() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello";
string s2 = "Hello";
string s3 = "Bye";
Console.WriteLine(s1.Equals(s2));
Console.WriteLine(s1.Equals(s3));
}
}

ICT Academy 21
C# String Format() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{

string s1 = string.Format("{0:D}", DateTime.Now);


Console.WriteLine(s1);
}
}

ICT Academy 22
C# String GetType() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
Console.WriteLine(s1.GetType());
}
}

ICT Academy 23
C# String IndexOf() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
int index = s1.IndexOf('e');
Console.WriteLine(index);
}
}

ICT Academy 24
C# String Insert() Method Example

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "Hello C#";
string s2 = s1.Insert(5,"-");
Console.WriteLine(s2);
}
}

ICT Academy 25
C#:Math Functions
The C# Math class has many methods that allows you to perform mathematical tasks on numbers.
Math.Max(x,y)
The Math.Max(x,y) method can be used to find the highest value of x and y:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Max(5, 10));
}
}}
Result : 10
ICT Academy 26
Math.Min(x,y)
The Math.Min(x,y) method can be used to find the lowest value of of x and y:

Math.Sqrt(x)
The Math.Sqrt(x) method returns the square root of x:

Math. Abs()
Returns the absolute value of a specified number.

Math. Acos()
Returns the angle whose cosine is the specified number.

Math. Acosh()
Returns the Inverse hyperbolic cosine of the specified number.

Math.Asinh()
Returns the Inverse hyperbolic sine of the specified number.
ICT Academy 27
Math.Celling()
Returns the smallest integral value greater than or equal to the specified number.

Math.Floor()
Returns the largest integral value less than or equal to the specified number.

Math.log()
Returns the logarithm of a specified number.

Math.log10()
Returns the base 10 logarithm of a specified number.

Math.Pow()
Returns a specified number raised to the specified power.

ICT Academy 28
Math.Round()
Rounds a value to the nearest integer or to the specified number of fractional digits.

Math.Sign()
Returns an integer that indicates the sign of a number.

Math.Sin()
Returns the sine of the specified angle.

Math.Sinh()
Returns the hyperbolic sine of the specified angle.

ICT Academy 29
Math. Tan()
Returns the tangent of the specified angle.

Math. Tanh()
Returns the hyperbolic tangent of the specified angle.

Math. Truncate()
Calculates the integral part of a number.

ICT Academy 30
using System;
public class GFG {
static public void Main()
{
Console.WriteLine("Floor value of 123.123: "+ Math.Floor(123.123))
Console.WriteLine("Asin value of 0.35: "+ Math.Asin(0.35));
Console.WriteLine("Square Root of 81: "+ Math.Sqrt(81));
Console.WriteLine("Round value of 14.6534: "Math.Round(14.6534));
}
}

Output:
Floor value of 123.123: 123
Asin value of 0.35: 0.35757110364551
Square Root of 81: 9
Round value of 14.6534: 15
ICT Academy 31
using System;

class Program {
static void Main() {
Console.WriteLine(Math.Acos(0));
Console.WriteLine(Math.Cos(2));

Console.WriteLine(Math.Asin(0.2));
Console.WriteLine(Math.Sin(2));
}
}

ICT Academy 32
var vals = new int[] { -1, 2, 0, -3, -2, 9, 7 };
foreach (var e in vals)
{Console.WriteLine(Math.Abs(e));}
Console.WriteLine("-----------------");
int sum = 0;
foreach (var e in vals)
{
sum += e;
}
Console.WriteLine(sum);
sum = 0;
foreach (var e in vals)
{
sum += Math.Abs(e);
}
Console.WriteLine(sum);

ICT Academy 33
decimal[] vals = { 6.07m, 6.64m, 0.12m, -0.12m, -6.13m, -6.65m };

Console.WriteLine("{0,7} {1,16} {2,14}",


"Numer", "Ceiling", "Floor");

foreach (var e in vals)


{
Console.WriteLine("{0,7} {1,16} {2,14}",
e, Math.Ceiling(e), Math.Floor(e));
}

int x = 3;
int y = 81;

double res = Math.Pow(x, 5);


Console.WriteLine(res);

res = Math.Sqrt(y);
Console.WriteLine(res);

res = Math.Cbrt(y);
Console.WriteLine(res);ICT Academy 34
long res = Math.BigMul(int.MaxValue, int.MaxValue);
Console.WriteLine(res);

long res2 = (long) int.MaxValue * int.MaxValue;


Console.WriteLine(res2);

int x = 10;
int y = 3;

int rem = 0;
double quo = Math.DivRem(x, y, out rem);

Console.WriteLine($"Quotient: {quo} Remainder: {rem}");

quo = x / y;
rem = x % y;

Console.WriteLine($"Quotient:
ICT Academy {quo} Remainder: {rem}"); 35
double radius = 5;

double circumference = 2 * Math.PI * radius;


Console.WriteLine(circumference);

double area = Math.PI * Math.Pow(radius, 2);


Console.WriteLine(area);

ICT Academy 36
Program for Practice In String Functions
  Find duplicate characters in a string.

 Get all unique characters in a string.

 Reverse a string.

 Reverse each word of the sentence (string).

 Get the word count in a sentence (string).

 Check if a string is a palindrome or not.

 Check max occurrence of a character in the string.

 Get all possible substring


ICT Academy in a string. 37
Programs for Practice in Math Functions
 Calculate the value that results from raising 3 to a power ranging from 0 to 32.

 Calculate true mean value, mean with rounding away from zero and mean with rounding to nearest of
some specified decimal values.

 Divide two given integers (dividend and divisor) and get the quotient without using multiplication,
division and mod operator.

ICT Academy 38

You might also like