How to get the indexes of words from an array of strings that start with a specific letter in C#

2 Answers

0 votes
using System;
using System.Collections.Generic;

public static class Extensions // Make a static and non-generic class
{
    public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
        int index = 0;
        foreach (T element in source) {
            if (predicate(element)) {
                yield return index;
            }
            index++;
        }
    }
}

public class Program
{
    public static void Main()
    {
        string[] s = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", 
                       "nine", "ten", "let\’s start again" };
        
        var indexes = s.IndexesWhere(t => t.StartsWith("t"));

        Console.Write(string.Join(", ", indexes));
    }
}


/*
run:

2, 3, 10

*/

 



answered Mar 13, 2025 by avibootz
0 votes
using System;
using System.Collections.Generic;

public class Program
{
    public static List<int> getIndexes(string[] s) {
        List<int> indexes = new List<int>();

        for (int i = 0; i < s.Length; i++) {
           if (s[i][0] == 't') {
              indexes.Add(i);
           }
        }
        
        return indexes;
    }
    
    public static void Main()
    {
        string[] s = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", 
                       "nine", "ten", "let\’s start again" };
                       
        List<int> indexes = getIndexes(s);

        Console.Write(string.Join(", ", indexes));
    }
}


/*
run:

2, 3, 10

*/

 



answered Mar 13, 2025 by avibootz
...