w3resource
C# Sharp Programming Exercises

C# Sharp Exercises: Search the position of a substring within a string

C# Sharp String: Exercise-17 with Solution

Write a program in C# Sharp to search the position of a substring within a string.

C# Sharp Exercises: Search the position of a substring within a string

Sample Solution:-

C# Sharp Code:

using System;

public class Exercise17
{
   public static void Main()
   {
   
       string str1;
	   string findstr;
       Console.Write("\n\nSearch the position of a substing within a string :\n");
       Console.Write("-------------------------------------------------------\n");    
			Console.Write("Input a String: ");
			str1 = Console.ReadLine();
 
			Console.Write("Input a substring to be found in the string: ");
			findstr = Console.ReadLine();   
      int index = str1.IndexOf(findstr);
	  if(index<0)
	  Console.WriteLine("The substring no found  in the given string \n");
	  else
      Console.WriteLine("Found '{0}' in '{1}' at position {2}",
                        findstr, str1, index);
   }
}

Sample Output:

Search the position of a substing within a string :                    
-------------------------------------------------------                
Input a String: Welcome to w3resource.com                              
Input a substring to be found in the string: w3resource                
Found 'w3resource' in 'Welcome to w3resource.com' at position 11

Flowchart:

Flowchart: Search the position of a substing within a string

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to check the username and password.
Next: Write a program in C# Sharp to check whether a character is an alphabet and not and if so, go to check for the case.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming