AlgoTales · Roadmap

String traversal

Beginner · 6 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

String traversal means walking through a piece of text one character at a time, from the first to the last. Almost every text feature relies on it: checking input, cleaning data, counting letters or reading a format character by character.

Practical use cases

  • Web app: Password rule checker. A sign-up form says a password needs a digit, a capital and a special character. The code walks along the typed password once, ticking off each rule as it sees a matching character. The green ticks update as the user types, without scanning the text three separate times.
  • Web app: Cleaning pasted phone numbers. A contact form receives numbers like +91 (98765) 43210. The code walks along the text and keeps only the digits, dropping spaces, brackets and dashes. One pass leaves a clean number that can be saved and compared. Every character is looked at only once.
  • System: Parsers and compilers. A JSON parser, a template engine and a compiler all read text one character at a time, deciding what each character means based on what came before. That plain walk is the first step of any language tool.

The story: The Banner Painter

Mira's cousin was getting married, and the family needed a welcome banner. Mira was given the brush and a sheet with one word on it: NAMASTE. "Paint it," said Auntie, "but slowly, one letter at a time, and never skip one."

Mira put her finger under the first letter, painted it, and slid her finger one step to the right. Then the next letter. Then the next. Her little brother Kabir wanted to help: "Can I count how many vowels there are?" Mira said, "Just walk beside me. Whenever my finger lands on A, E, I, O or U, add one to your count."

When her finger slid off the last letter, there was nothing left to paint, and Kabir shouted "3 vowels!" Nobody had to go back, nobody had to guess. That finger-sliding walk from the first letter to the last is called string traversal, and almost every string trick you will ever learn begins with it.

How to spot this problem, and where you need it

You have to inspect, clean or validate text one character at a time, and your code uses clumsy repeated checks or several passes over the same string.

Signs you need it

  • The task says validate the format, remove unwanted characters, count characters or check each letter.
  • You are calling several string functions over the same text, each of which walks through it separately.
  • Multibyte characters, such as Hindi letters or emojis, are being cut in half or counted wrongly.

Where to use it in a project

  • Form validation: passwords, usernames, coupon codes, PAN and GST style identifiers.
  • Input cleaning, such as stripping symbols from phone numbers, normalising names, and building simple parsers.

The solution

Step through the text from the first position to the last, looking at one character at a time. Keep any needed state in variables, such as a flag for seen a digit, a counter, or a result string being built. Update them as you go, so everything is gathered in one pass. In PHP or JavaScript, use a multibyte-safe approach if the text may contain non-English characters.

Payoff: Before: three passes and three regular expressions for a password. After: one pass that checks all rules and gives live feedback.

Explain it like I am 8

A word is a train of little coaches, and each coach holds one letter. To look at the word, you walk from the first coach to the last, peeking into every coach once. That walk is traversal.

How it works, step by step

  1. Start at position 0. Strings count from zero, so the first letter lives at s[0].
  2. Ask for the length once, so you know where the train ends.
  3. Walk with a loop: for i from 0 up to length - 1, and look at s[i].
  4. Do your small job on each letter: count it, compare it, collect it.
  5. Stop when i reaches the length. There is no letter there, so touching it is a bug.

The code in four languages

PHP

<?php
// Walk over a string once and count the vowels.
function countVowels(string $s): int {
    $count = 0;
    $n = strlen($s);                      // ask for the length once
    for ($i = 0; $i < $n; $i++) {         // i goes 0 .. n-1
        $ch = $s[$i];                     // the letter at position i
        if (str_contains('AEIOU', strtoupper($ch))) {
            $count++;
        }
    }
    return $count;
}

$word = "Namaste";
for ($i = 0; $i < strlen($word); $i++) {
    echo $i . ':' . $word[$i] . ' ';      // 0:N 1:a 2:m ...
}
echo "\n";
echo "Vowels: " . countVowels($word) . "\n";   // 3

JavaScript

// Walk over a string once and count the vowels.
function countVowels(s) {
  let count = 0;
  for (let i = 0; i < s.length; i++) {    // i goes 0 .. length-1
    const ch = s[i];                      // the letter at position i
    if ('AEIOU'.includes(ch.toUpperCase())) {
      count++;
    }
  }
  return count;
}

const word = 'Namaste';
let line = '';
for (let i = 0; i < word.length; i++) {
  line += i + ':' + word[i] + ' ';        // 0:N 1:a 2:m ...
}
console.log(line);
console.log('Vowels: ' + countVowels(word));   // 3

Java

public class Main {
    // Walk over a string once and count the vowels.
    static int countVowels(String s) {
        int count = 0;
        int n = s.length();                   // ask for the length once
        for (int i = 0; i < n; i++) {         // i goes 0 .. n-1
            char ch = s.charAt(i);            // the letter at position i
            if ("AEIOU".indexOf(Character.toUpperCase(ch)) >= 0) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String word = "Namaste";
        StringBuilder line = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            line.append(i).append(':').append(word.charAt(i)).append(' ');   // 0:N 1:a 2:m ...
        }
        System.out.println(line);
        System.out.println("Vowels: " + countVowels(word));   // 3
    }
}

Go

package main

import (
	"fmt"
	"strings"
	"unicode"
)

// countVowels walks over a string once and counts the vowels.
func countVowels(s string) int {
	count := 0
	n := len(s)              // ask for the length once
	for i := 0; i < n; i++ { // i goes 0 .. n-1
		ch := rune(s[i]) // the letter at position i
		if strings.ContainsRune("AEIOU", unicode.ToUpper(ch)) {
			count++
		}
	}
	return count
}

func main() {
	word := "Namaste"
	line := ""
	for i := 0; i < len(word); i++ {
		line += fmt.Sprintf("%d:%c ", i, word[i]) // 0:N 1:a 2:m ...
	}
	fmt.Println(line)
	fmt.Println("Vowels:", countVowels(word)) // 3
}

Time: O(n) · Extra space: O(1). One visit per letter, and we only keep a single counter.

Watch out for

  • Running the loop to i <= length. The last valid position is length - 1.
  • Forgetting that letters outside plain English (Hindi, emoji) can take several bytes: strlen in PHP counts bytes, so use mb_strlen and mb_substr for such text.

Quick check

  1. In "NAMASTE", at which position is the first letter?
    • 1
    • 0
    • -1
  2. How many times does a single traversal look at each letter?
    • Once
    • Twice
    • As many times as the length
  3. A word has 7 letters. What is the last valid position?
    • 7
    • 8
    • 6