Tuesday, 31 October 2023

C# String data type : Exercises

 C# String data type : Exercises, Practice, Solution

Write a C# Sharp program to find the length of a string without using a library function.

  using System;  
  public class Exercise2
  {  
      public static void Main()
  {
      string str; /* Declares a string of size 100 */
      int l= 0;
   
        Console.Write("Input the string : ");
        str = Console.ReadLine();
 
           foreach(char chr in str)
          {
              l += 1;
          }
     Console.Write("Length of the string is : {0}\n\n", l);
    }
  }

Write a program in C# Sharp to count the total number of words in a string.

  using System;  
  public class Exercise5
  {  
      public static void Main()
      {
          string str;
          int i, wrd,l;
   
            Console.Write("Input the string : ");
            str = Console.ReadLine();
   
             l = 0;
             wrd = 1;
 
      /* loop till end of string */
      while (l <= str.Length - 1)
      {
          /* check whether the current character is white space or new line or tab character*/
          if(str[l]==' ' || str[l]=='\n' || str[l]=='\t')
          {
              wrd++;
          }
 
          l++;
      }
 
     Console.Write("Total number of words in the string is : {0}\n", wrd);
    }
  }

Write a program in C# Sharp to compare two strings without using a string library functions.

  using System;  
  public class Exercise6
  {  
      public static void Main()
  {
      string str1, str2;
      int flg=0;
      int i = 0, l1, l2, yn = 0;
     
        Console.Write("Input the 1st string : ");
        str1 = Console.ReadLine();    
       
        Console.Write("Input the 2nd string : ");
        str2 = Console.ReadLine();    
 
      l1=str1.Length;
      l2=str2.Length;
      /*compare checking when they are equal in length*/    
      if(l1==l2)
    {
      for(i=0;i<l1;i++)
        {
            if(str1[i] != str2[i])
            {
              yn= 1;
              i= l1;       
            }
        }
    }
  /*initialize the flag where they are equal, smaller and greater in length*/  
      if(l1 == l2)
          flg=0;
      else if(l1 > l2)
          flg=1;
      else if(l1 < l2)
          flg=-1;
  /*display the message where the strings are same or smaller or greater*/  
      if(flg == 0)
      {
         if(yn==0)
         Console.Write("\nThe length of both strings are equal and \nalso, both strings are same.\n\n");
         else
              Console.Write("\nThe length of both strings are equal \nbut they are not same.\n\n");
      }
      else if(flg == -1)
      {
         Console.Write("\nThe length of the first string is smaller than second.\n\n");
      }
      else
      {
         Console.Write("\nThe length of the first string is greater than second.\n\n");
      }
    }
  }

Write a program in C# Sharp to count the number of alphabets, digits and special characters in a string.

using System;  
  public class Exercise7  
  {  
   public static void Main()
  {
      string str;
      int alp, digit, splch, i,l;
      alp = digit = splch = i = 0;
 
        Console.Write("Input the string : ");
        str = Console.ReadLine();
        l=str.Length;
 
       /* Checks each character of string*/
 
      while(i<l)
      {
          if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              alp++;
          }
          else if(str[i]>='0' && str[i]<='9')
          {
              digit++;
          }
          else
          {
              splch++;
          }
 
          i++;
      }
 
     Console.Write("Number of Alphabets in the string is : {0}\n", alp);
     Console.Write("Number of Digits in the string is : {0}\n", digit);
     Console.Write("Number of Special characters in the string is : {0}\n\n", splch);
    }
  }

Write a program in C# Sharp to copy one string to another string.

using System;  
public class Exercise8  
{  
    public static void Main()
{
    string str1;
    int  i,l;

      Console.Write("\n\nCopy one string into another string :\n");
      Console.Write("-----------------------------------------\n");  
      Console.Write("Input the string : ");
      str1 = Console.ReadLine();
     
      l=str1.Length;
      string[] str2=new string[l];

    /* Copies string1 to string2 character by character */
    i=0;
    while(i<l)
    {
        string tmp=str1[i].ToString();
        str2[i] = tmp;
        i++;
    }
   Console.Write("\nThe First string is : {0}\n", str1);
   Console.Write("The Second string is : {0}\n", string.Join("",str2));
   Console.Write("Number of characters copied : {0}\n\n", i);
  }
}

Write a C# Sharp program to count the number of vowels or consonants in a string.

  public class Exercise9  
  {  
  public static void Main()
  {
      string str;
      int i, len, vowel, cons;
     
      Console.Write("Input the string : ");
      str = Console.ReadLine();  
 
      vowel = 0;
      cons = 0;
      len = str.Length;
 
      for(i=0; i<len; i++)
      {
 
          if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
          {
              vowel++;
          }
          else if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
          {
              cons++;
          }
      }
     Console.Write("\nThe total number of vowel in the string is : {0}\n", vowel);
     Console.Write("The total number of consonant in the string is : {0}\n\n", cons);
    }
  }

Write a C# Sharp program to find the maximum number of characters in a string.  Click here

Find the character and Number of Occurrence in given word where number of Occurrence is more then 1

            string val = "Interview";

            Dictionary<string, int> dict = new Dictionary<string, int>();
            for (int i = 0; i < val.Length; i++)
            {
                string c = val[i].ToString().ToLower();
                if (dict.ContainsKey(c))
                {
                    dict[c] = dict[c] + 1;
                }
                else
                {
                    dict[c] = 1;
                }
            }

            foreach (var d in dict.Where(x=> x.Value > 1))
            {
                Console.WriteLine("Key: "+d.Key+" Value: "+d.Value);
            }

Output:

Key: i Value: 2

Key: e Value: 2


Continue Reading →

Monday, 30 October 2023

Arrays in C#

In C#, an array is a collection of elements of the same type that are stored in contiguous memory locations and can be accessed using an index. Arrays provide an efficient way of storing and accessing a fixed number of elements.

 Create an array 

There are multiple ways to create an array in C#. Here are a few examples.

Using the new keyword

  int[] numbers = new int[5];

The above code snippet creates an array called "intArray" to hold five integers. However, the elements of the Array are not yet initialized, and their values are undefined.

Using the new keyword with an array initializer

Arrays can also be initialized when they are declared by providing a list of comma-separated values enclosed in curly braces {}

  int[] intArray = new int[] {1, 2, 3, 4, 5};

  // or Simply
 
  int[] intArray = {1, 2, 3, 4, 5};

This creates an array called "intArray" with five elements and assigns the values 1, 2, 3, 4, and 5 to the elements of the Array.

Using the var keyword

  var myArray = new int[] {1, 2, 3, 4, 5};

This creates an array; the array type is inferred from the initializer, and the Array's name is myArray.

How To Sort Array In C#

The simplest way to sort an array in C# is using Array.Sort method. The Array.Sort method takes a one-dimensional array as an input and sorts the array elements in the ascending order.

The following code snippet creates an array of integers.

  int[] intArray = new int[] { 9, 2, 4, 3, 1, 5 };

The Array.Sort method takes array as an input and sorts the array in ascending order.

  Array.Sort(intArray);

To sort an array in descending order, we can use Sort.Reverse method. This method also takes an array as an input and sorts its elements in descending order. The following code snippet reverses an array.

  Array.Reverse(intArray);

Sort an Array of Int in C#

Here is the complete code that creates an array of integers and sorts in ascending and descending orders using Array.Sort and Array.Reverse methods.

static void Main(string[] args) {
    // Array of integers
    int[] intArray = new int[] {
        9,
        2,
        4,
        3,
        1,
        5
    };
    Console.WriteLine("Original array");
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    // Sort array in ASC order
    Console.WriteLine("Sorted array in ASC order");
    Array.Sort(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();
    Console.WriteLine("Sorted array in DESC order");
    // Sort Array in DESC order
    Array.Reverse(intArray);
    foreach(int i in intArray) {
        Console.Write(i + " ");
    }
    Console.WriteLine();

The output of the above code is below where first it prints the original array, followed by the sorted array in ASC and DESC order respectively.


Sort an Array of Strings in C#

Now let’s sort an array of strings in C#. Sorting an array of strings is like sorting an array of int. The Array.Sort method takes an input value of an array of strings. The following code example shows how to sort an array of strings in ascending and descending orders using C#.

  // Array of strings
string[] strArray = new string[] { "Mahesh", "David", "Allen", "Joe", "Monica" };
Console.WriteLine();
Console.WriteLine("Original array");
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
// Sort array
Array.Sort(strArray);
// Read array items using foreach loop
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();
Array.Reverse(strArray);
foreach (string str in strArray)
{
    Console.Write(str + " ");
}
Console.WriteLine();

The output of the above code displays original array, sorted array in the ascending order, and sorted array in the descending order.


Sort a Range of Elements In An Array

The Sort.Array method allows you to sort a range of elements within an array. For example, if an array has 11 elements but what if you want to sort only 1st to next 6 elements in the array? You can use that by passing the first starting index of the element followed by the number of elements to be sorted.

// Array of integers
int[] intArray = new int[] { 9, 2, 4, 3, 1, 5, 6, 9, 5, 7, 1, 0};
// Sort array from 1st element to 6th element. Skip 0th element.
Array.Sort(intArray, 1, 6);
foreach (int i in intArray)
{
    Console.Write(i + " ");
}

The output looks like the following where you can see only 6 elements are sorted after skipping the first element of the array.

9 1 2 3 4 5 6 9 5 7 1 0

Note that this sorting applies to all types of arrays not just integers.


Continue Reading →

Sunday, 8 October 2023

HTML5 Features

 Top HTML5 Features are:

HTML stands for Hyper Text markup language, and HTML 5 is the 5th version of it. A lot of dynamic parameters were missing in the HTML for which we have to depend on third-party libraries, however, in the latest version of HTML it has become a lot easier for building a dynamic website.

Browser support for HTML5

All modern browsers, including Google Chrome, Mozilla Firefox, Opera Mini, Microsoft Edge, and Apple Safari, support HTML 5 in all of their features. Because HTML 5 capabilities are not adequately supported by earlier browser versions, developers must create alternative content to ensure cross-browser compatibility. 

below are the list of Top HTML5 Features, which are described in detail below:

  1. Semantic Elements
  2. Audio and Video Support
  3. Canvas Elements
  4. Geolocation API
  5. Local Storage
  6. Responsive Images
  7. Web Workers
  8. Drag and Drop API
  9. Form Enhancements
  10. Web Sockets
  11. Micro Data
  12. Cross Document Messaging
For details, visit website

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives