How to search string from the right (reverse) in C#

3 Answers

0 votes
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = "Star Wars is great movie";

                int i = s.LastIndexOf('i');
	            if (i != -1)
	            {
	                Console.WriteLine(i);
	                Console.WriteLine(s.Substring(i));
	            }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
  
22
ie
 
*/


answered Mar 28, 2015 by avibootz
edited Feb 7, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = "Star Wars is great movie. Star Trek is also a great movie";

                int i = s.LastIndexOf("great");
	            if (i != -1)
	            {
	                Console.WriteLine(i);
	                Console.WriteLine(s.Substring(i));
	            }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
  
46
great movie
 
*/


answered Mar 28, 2015 by avibootz
edited Feb 7, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = "Star Wars is GREAT movie. Star Trek is also a Great movie";

                // ignor the case
                int i = s.LastIndexOf("great", StringComparison.OrdinalIgnoreCase); 
                if (i != -1)
                {
                    Console.WriteLine(i);
                    Console.WriteLine(s.Substring(i));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
   
46
Great movie
  
*/


answered Mar 28, 2015 by avibootz
edited Feb 7, 2016 by avibootz
...