How do I remove a portion of text from a string?

Category: System, viewed: 816 time(s).

This example demonstrate the use of String.Remove() and StringBuilder.Remove() methods to eliminate some part out of a string.

using System;
using System.Text;

namespace Kodecsharp.Example.System
{
    public class RemoveSubstring
    {
        public static void Main(string[] args)
        {
            string originalText = "Windows XP Professional - VMware Server Console";
            Console.WriteLine("Text = " + originalText);

            //
            // Removing string from the 23rd index to the end of the string
            //
            string text = originalText.Remove(23);
            Console.WriteLine("Text = " + text);

            //
            // Removing 13 characters from the string starting from the 10th
            // index.
            //
            text = originalText.Remove(10, 13);
            Console.WriteLine("Text = " + text);

            //
            // We can also use the StringBuilder class which have the same
            // Remove() method.
            //
            StringBuilder builder = new StringBuilder(originalText);

            //
            // Remove the VMware substring.
            //
            builder.Remove(26, 7);
            Console.WriteLine("Text = " + builder.ToString());

            Console.ReadLine();
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page