Going further · 19
Working with strings
Slicing, finding, replacing, trimming, comparing and padding.
Once input comes in, you often trim it (drop spaces at both ends), find and cut out the part you need, and change its shape before printing.
The example below uses those tools one by one.
text = input().strip()date = input()a, b = input().split()n = input().strip()print(f"[{text}]")print(text[:5])i = text.find("World")print(i)print(text[i:i + 5])print(text.find("Bye"))print(date.replace("-", "/"))print((a > b) - (a < b))print(n.rjust(3, "0"))const lines = require("fs").readFileSync(0, "utf8").split("\n");const text = lines[0].trim();const date = lines[1].trim();const [a, b] = lines[2].trim().split(" ");const n = lines[3].trim();console.log(`[${text}]`);console.log(text.slice(0, 5));const i = text.indexOf("World");console.log(i);console.log(text.slice(i, i + 5));console.log(text.indexOf("Bye"));console.log(date.replaceAll("-", "/"));console.log(a < b ? -1 : a > b ? 1 : 0);console.log(n.padStart(3, "0"));import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const text: string = lines[0].trim();const date: string = lines[1].trim();const [a, b]: string[] = lines[2].trim().split(" ");const n: string = lines[3].trim();console.log(`[${text}]`);console.log(text.slice(0, 5));const i: number = text.indexOf("World");console.log(i);console.log(text.slice(i, i + 5));console.log(text.indexOf("Bye"));console.log(date.replaceAll("-", "/"));console.log(a < b ? -1 : a > b ? 1 : 0);console.log(n.padStart(3, "0"));import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String text = sc.nextLine().strip(); String date = sc.nextLine().strip(); String[] ab = sc.nextLine().strip().split(" "); String n = sc.nextLine().strip(); System.out.println("[" + text + "]"); System.out.println(text.substring(0, 5)); int i = text.indexOf("World"); System.out.println(i); System.out.println(text.substring(i, i + 5)); System.out.println(text.indexOf("Bye")); System.out.println(date.replace("-", "/")); System.out.println(Integer.signum(ab[0].compareTo(ab[1]))); System.out.println("0".repeat(Math.max(0, 3 - n.length())) + n); }}using System; class Program{ static void Main() { string text = Console.ReadLine().Trim(); string date = Console.ReadLine().Trim(); string[] ab = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); string n = Console.ReadLine().Trim(); Console.WriteLine($"[{text}]"); Console.WriteLine(text.Substring(0, 5)); int i = text.IndexOf("World", StringComparison.Ordinal); Console.WriteLine(i); Console.WriteLine(text.Substring(i, 5)); Console.WriteLine(text.IndexOf("Bye", StringComparison.Ordinal)); Console.WriteLine(date.Replace("-", "/")); Console.WriteLine(Math.Sign(string.CompareOrdinal(ab[0], ab[1]))); Console.WriteLine(n.PadLeft(3, '0')); }}#include <iomanip>#include <iostream>#include <string> std::string trim(const std::string& s) { size_t start = s.find_first_not_of(" \t\r\n"); if (start == std::string::npos) return ""; size_t end = s.find_last_not_of(" \t\r\n"); return s.substr(start, end - start + 1);} int main() { std::string text, date, a, b, n; std::getline(std::cin, text); std::getline(std::cin, date); std::cin >> a >> b >> n; text = trim(text); date = trim(date); std::cout << '[' << text << "]\n"; std::cout << text.substr(0, 5) << '\n'; size_t i = text.find("World"); std::cout << i << '\n'; std::cout << text.substr(i, 5) << '\n'; size_t miss = text.find("Bye"); std::cout << (miss == std::string::npos ? -1 : (long)miss) << '\n'; for (size_t p; (p = date.find('-')) != std::string::npos;) date.replace(p, 1, "/"); std::cout << date << '\n'; int c = a.compare(b); std::cout << (c > 0) - (c < 0) << '\n'; std::cout << std::setw(3) << std::setfill('0') << n << '\n';}#include <ctype.h>#include <stdio.h>#include <string.h> char *trim(char *s) { while (isspace((unsigned char)*s)) s++; char *end = s + strlen(s); while (end > s && isspace((unsigned char)end[-1])) *--end = '\0'; return s;} int main(void) { char line[1024], date[64], a[64], b[64]; int n; fgets(line, sizeof line, stdin); scanf("%63s %63s %63s %d", date, a, b, &n); char *text = trim(line); printf("[%s]\n", text); printf("%.5s\n", text); char *found = strstr(text, "World"); int i = found ? (int)(found - text) : -1; printf("%d\n", i); printf("%.5s\n", text + i); printf("%d\n", strstr(text, "Bye") ? (int)(strstr(text, "Bye") - text) : -1); for (char *p = date; *p; p++) if (*p == '-') *p = '/'; printf("%s\n", date); int c = strcmp(a, b); printf("%d\n", (c > 0) - (c < 0)); printf("%03d\n", n); return 0;}text = Console.ReadLine().Trim();date = Console.ReadLine().Trim();ab = Console.ReadLine().Split();n = Console.ReadLine().Trim();Console.WriteLine("[" + text + "]");Console.WriteLine(text.Substring(0, 5));i = text.IndexOf("World");Console.WriteLine(i);Console.WriteLine(text.Substring(i, 5));Console.WriteLine(text.IndexOf("Bye"));Console.WriteLine(date.Replace("-", "/"));if (ab[0] < ab[1]){ Console.WriteLine(-1);}else if (ab[0] > ab[1]){ Console.WriteLine(1);}else{ Console.WriteLine(0);}Console.WriteLine(n.PadLeft(3, "0"));Hello, World 2026-11-10 pear apple 7
[Hello, World] Hello 7 World -1 2026/11/10 1 007
Key points
- Trimming drops spaces at both ends.
Trimming every line you read is the safe habit. - Finding returns the position of the first match.
With no match most languages give -1, but not all. - When slicing, the second number means different things: an end position (not included) in some languages, a length in others.
- Replacing changes every match in most languages, but JavaScript
replacechanges only the first. - Comparing returns negative, 0 or positive.
Trust only the sign; the size means nothing. - Padding fills the front to a fixed width, turning
7into007.
How each language writes it
| Python | strip(), find (-1 if missing; index raises an error), t[7:12] (end position), replace (all), rjust(3, "0") |
|---|---|
| JavaScript | trim(), indexOf, slice(7, 12) (end position), replace first only and replaceAll for all, padStart(3, "0").localeCompare follows the locale |
| TypeScript | Same as JavaScript |
| Java | strip(), indexOf, substring(7, 12) (end position), replace (all; replaceAll takes a regex), compareTo (trust only the sign) |
| C# | Trim(), IndexOf, Substring(7, 5) (length), Replace (all), PadLeft(3, '0').string.Compare and IndexOf(string) follow the culture; for raw character codes add StringComparison.Ordinal or use string.CompareOrdinal |
| C++ | No trim, so cut it yourself.find (std::string::npos if missing), substr(7, 5) (length), compare.Replace-all is a loop. Pad with setw and setfill |
| C | No trim or replace-all; do them yourself.strstr (NULL if missing), slice with printf("%.5s", text + 7) (start address and length), compare with strcmp, pad with printf("%03d") |
| Craykon | Trim(), IndexOf (-1 if missing), Substring(7, 5) (length), Replace (all), PadLeft(3, "0") |
Common mistakes
Expecting compareTo to return 1Java · C · C++ · C#
System.out.println("pear".compareTo("apple"));→ 15 — it is 'p' - 'a'
Look only at the sign, as in > 0 or < 0.
Mixing up the second slicing numberC# · Java · JavaScript
"Hello, World".Substring(7, 12) // C#
"Hello, World".substring(7, 5) // Java, JavaScript→ C# throws an out-of-range error, and so does Java. JavaScript quietly swaps the two numbers and returns ", "
Check whether the second number is an end position or a length in that language.
Expecting replace to change every matchJavaScript · TypeScript
console.log("2026-11-10".replace("-", "/"));→ 2026/11-10 — only the first one changed
Use replaceAll for all of them.
Watch out in Java too: replaceAll takes a regex, so "a.b".replaceAll(".", "-") is "---".
How languages differ
Input made on Windows ends lines with
Java
Input made on Windows ends lines with
\r\n.Java
nextLine(), C# ReadLine() and Craykon ReadLine() strip the \r, but Python input() (on Linux and macOS), JavaScript split("\n"), C fgets and C++ getline keep it, so "World\r" == "World" is false; trim the lines you read.