Substring

5 snippets across 5 stacks — Bash & Linux, Interview Prep, JavaScript, Python, SQL

SHBash & Linux

String Operations

SH · Bash Scripting
syntax
${#string}          # length
${string:offset:length}  # substring
${string/pattern/replacement}
example
FILEPATH="/opt/app/logs/server.log"
echo "Length: ${#FILEPATH}"
echo "Filename: ${FILEPATH##*/}"
echo "Directory: ${FILEPATH%/*}"
echo "Change ext: ${FILEPATH%.log}.txt"

URL="https://api.example.com"
echo "${URL/#https/http}"
output
Length: 26
Filename: server.log
Directory: /opt/app/logs
Change ext: /opt/app/logs/server.txt
http://api.example.com

Note ## removes longest prefix match, # removes shortest. %% removes longest suffix, % removes shortest. These are pure Bash operations (no subprocess), so they are much faster than calling sed or basename in a loop.

DSAInterview Prep

Sliding Window

DSA · Arrays & Strings
syntax
Maintain a window [left..right] and expand/shrink to satisfy a condition.
Fixed-size window: move both pointers together.
Variable-size window: expand right, shrink left when constraint violated.
example
// JavaScript — Max sum subarray of size k
function maxSumWindow(arr, k) {
  let windowSum = 0, maxSum = -Infinity;
  for (let i = 0; i < arr.length; i++) {
    windowSum += arr[i];
    if (i >= k) windowSum -= arr[i - k];
    if (i >= k - 1) maxSum = Math.max(maxSum, windowSum);
  }
  return maxSum;
}

# Python — Max sum subarray of size k
def max_sum_window(arr, k):
    window_sum = 0
    max_sum = float('-inf')
    for i in range(len(arr)):
        window_sum += arr[i]
        if i >= k:
            window_sum -= arr[i - k]
        if i >= k - 1:
            max_sum = max(max_sum, window_sum)
    return max_sum
output
max_sum_window([2,1,5,1,3,2], 3) → 9 (subarray [5,1,3])

Note Time O(n), Space O(1). Sliding window converts O(n*k) brute force to O(n). For variable-size windows (e.g., longest substring without repeats), use a hash set to track window contents. Always clarify: is the window fixed or variable size?

JSJavaScript

Extracting Substrings

JS · Strings
syntax
str.slice(start, end)
str.substring(start, end)
example
const path = "/users/profile/avatar.png";
console.log(path.slice(1));          // "users/profile/avatar.png"
console.log(path.slice(-10));        // "avatar.png"
console.log(path.slice(7, 14));      // "profile"

Note slice() supports negative indices (counts from end). substring() does not. Prefer slice() -- it is more predictable.

PYPython

String Slicing

PY · Strings
syntax
string[start:stop:step]
example
word = "pythonic"
print(word[0:4])
print(word[-4:])
print(word[::2])
print(word[::-1])
output
pyth
onic
ptoi
cinohtyp

Note Slicing never raises IndexError, even if indices exceed the string length. Negative step reverses direction.

SQLSQL

SUBSTRING

SQL · String Functions
syntax
SUBSTRING(string FROM start FOR length)
SUBSTRING(string, start, length)
example
SELECT
  SUBSTRING(phone FROM 1 FOR 3) AS area_code,
  SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain
FROM users;
output
-- area_code | domain
-- 206       | example.com

Note Positions are 1-based in SQL (not 0-based like most programming languages). The FROM/FOR syntax is ANSI; the comma syntax works in MySQL and PostgreSQL.