Returns all the locations of a char in a string - CSharp System

CSharp examples for System:Char

Description

Returns all the locations of a char in a string

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System;/*  w  ww .  java  2s . c  o m*/

public class Main{
        //Returns all the locations of a char in a string
        //Hello, l -> 2, 3
        //Hello, o -> 4
        //Bob, 1 -> -1
        public static int[] IndexOfAll(string input, string chars)
        {
            List<int> indices = new List<int>();
            for (int i = 0; i < input.Length; i++)
            {
                if (input.Substring(i, 1) == chars)
                    indices.Add(i);
            }

            if (indices.Count == 0)
                indices.Add(-1);

            return indices.ToArray();
        }
}

Related Tutorials