Start learning free

LESSON 222 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Lengths in C#: Building a List with foreach

Practice Read the full explanation

Given a List of strings words, return a List of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in C#, explained

    Problem overview

    The method WordLengths receives a List<string> named words and returns a List<int> with the length of every word, in the same order. Each word produces exactly one number, so the result is as long as the input.

    For ["I", "love", "pancakes"] the result is [1, 4, 8]. For ["banana", "kiwi", "fig"] it is [6, 4, 3]. A list with the single word "code" gives [4]. Uppercase and lowercase letters count the same: "Code" and "CODE" both have length 4.

    Approach: transform every item

    This is the "map" pattern: every input item becomes one output item. You don't skip anything and you don't combine items. The plan is to start with an empty result list, visit the words one by one, and add each word's length at the end of the result. Because both lists are filled from first to last, the lengths keep the order of the words.

    The result holds integers, so its type is List<int>. A List<int> stores plain int values and is the type the method promises to return, so it can't be swapped for a list of strings.

    Followed on the first example, lengths is empty at the start. After "I" it holds 1, after "love" it holds 1 and 4, and after "pancakes" it holds 1, 4 and 8. That is the list the method returns. Each pass through the loop does the same small job, which is why the body is a single line.

    Step by step

    1. Create an empty List<int> named lengths. It starts empty because the numbers arrive one at a time.
    2. Write a foreach loop with a string named word over words. A foreach loop goes over a List just as it goes over an array, and it runs once per word.
    3. Add word.Length to lengths with Add. Length is the number of characters in the string.
    4. Return lengths after the loop. Returning inside the loop would end the method after the first word, and only one length would come back.

    The solution in C#

    class Solution {
        public List<int> WordLengths(List<string> words) {
            List<int> lengths = new List<int>();
            foreach (string word in words) {
                lengths.Add(word.Length);
            }
            return lengths;
        }
    }

    Things to notice:

    • A string has a Length property, with no parentheses. A List has Count instead, so words.Count is the number of words and word.Length is the number of characters in one of them.
    • Add appends at the end, which is what keeps the order.
    • The loop never changes words. Changing a list while a foreach goes over it throws an exception, but here only lengths grows.

    Edge cases and common mistakes

    • Mixing up Length and Count. word.Count doesn't compile for a plain string, and words.Length doesn't compile for a List.
    • Returning too early. Put the return after the closing brace of the loop.
    • Counting the words instead of the letters. The result has one number for each word, and each number is that word's number of characters.
    • An empty string. It has length 0, and the method adds a 0 for it. The lesson's inputs always have at least one word.

    Testing

    wordsResult
    ["I", "love", "pancakes"][1, 4, 8]
    ["banana", "kiwi", "fig"][6, 4, 3]
    ["Code", "CODE", ""][4, 4, 0]
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free