Left of the n'th occurrence of c - CSharp System

CSharp examples for System:String Search

Description

Left of the n'th occurrence of c

Demo Code

/*//w  w w.  j a va  2  s  .c  o  m
 * @version   : 2.5.0
 * @author    : Ext.NET, Inc. http://www.ext.net/
 * @date      : 2014-10-20
 * @copyright : Copyright (c) 2008-2014, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
 * @license   : See license.txt and http://www.ext.net/license/. 
 * @website   : http://www.ext.net/
 */
using System.Web.UI;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;
using System;

public class Main{
        /// <summary>
        /// Left of the n'th occurrence of c
        /// </summary>
        public static string LeftOf(this string text, char c, int n)
        {
            if (text.IsEmpty())
            {
                return text;
            }

            int i = -1;
            
            while (n != 0)
            {
                i = text.IndexOf(c, i + 1);
                if (i == -1)
                {
                    return text;
                }
                --n;
            }
            
            return text.Substring(0, i);
        }
        /// <summary>
        /// Left of the first occurrence of text
        /// </summary>
        public static string LeftOf(this string text, string value)
        {
            if (text.IsEmpty())
            {
                return text;
            }

            int i = text.IndexOf(value);
            
            if (i == -1)
            {
                return text;
            }

            return text.Substring(0, i);
        }
        /// <summary>
        /// Left of the first occurrence of c
        /// </summary>
        public static string LeftOf(this string text, char c)
        {
            if (text.IsEmpty())
            {
                return text;
            }

            int i = text.IndexOf(c);
            
            if (i == -1)
            {
                return text;
            }

            return text.Substring(0, i);
        }
        /// <summary>
        /// Determine is the string is null or empty.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool IsEmpty(this string text)
        {
            return string.IsNullOrEmpty(text);
        }
}

Related Tutorials