String Functions¶
String manipulation and text processing functions. Most are instance methods called on string values.
Case Conversion¶
.ToUpper()¶
Converts string to uppercase.
Signature:
Parameters: None
Returns: (string) Uppercase string
Examples:
text = "hello world";
upper = text.ToUpper(); // "HELLO WORLD"
name = "alice";
display = name.ToUpper(); // "ALICE"
// Case-insensitive comparison
if (input.ToUpper() == "YES") {
// Matches "yes", "YES", "Yes", etc.
}
.ToLower()¶
Converts string to lowercase.
Signature:
Parameters: None
Returns: (string) Lowercase string
Examples:
text = "HELLO WORLD";
lower = text.ToLower(); // "hello world"
email = "USER@EXAMPLE.COM";
normalized = email.ToLower(); // "user@example.com"
// Normalize for comparison
if (status.ToLower() == "active") {
// Process
}
Whitespace¶
.Trim()¶
Removes leading and trailing whitespace.
Signature:
Parameters: None
Returns: (string) Trimmed string
Examples:
text = " hello world ";
trimmed = text.Trim(); // "hello world"
input = "\t\n data \n\t";
clean = input.Trim(); // "data"
// Clean user input
username = userInput.Trim();
// Check for empty after trim
if (input.Trim() == "") {
// Effectively empty
}
String Splitting¶
.Split(separator)¶
Splits string into array by separator.
Signature:
Parameters:
separator(string): Delimiter string
Returns: (InstanceArray) Array of strings
Examples:
csv = "apple,banana,cherry";
items = csv.Split(","); // ["apple", "banana", "cherry"]
sentence = "hello world from eversharp";
words = sentence.Split(" "); // ["hello", "world", "from", "eversharp"]
// Process parts
email = "user@example.com";
parts = email.Split("@");
username = parts[0]; // "user"
domain = parts[1]; // "example.com"
// Split by multiple characters
data = "a::b::c";
items = data.Split("::"); // ["a", "b", "c"]
String Searching¶
.Contains(substring)¶
Checks if string contains substring.
Signature:
Parameters:
substring(string): Text to search for
Returns: (boolean) True if found, false otherwise
Examples:
text = "hello world";
hasWorld = text.Contains("world"); // true
hasEversharp = text.Contains("eversharp"); // false
// Case-sensitive
text = "Hello World";
hasHello = text.Contains("hello"); // false (case mismatch)
hasHelloLower = text.ToLower().Contains("hello"); // true
// Validation
email = "user@example.com";
isValid = email.Contains("@") && email.Contains(".");
// Filter
messages.Filter((m) => m.text.Contains("urgent"));
.StartsWith(prefix)¶
Checks if string starts with prefix.
Signature:
Parameters:
prefix(string): Prefix to check
Returns: (boolean) True if starts with prefix, false otherwise
Examples:
text = "hello world";
startsWithHello = text.StartsWith("hello"); // true
startsWithWorld = text.StartsWith("world"); // false
// Check protocol
url = "https://example.com";
isSecure = url.StartsWith("https://"); // true
// Filter by prefix
policies = allPolicies.Filter((p) => p.number.StartsWith("POL-"));
// Case-sensitive
text = "Hello";
starts = text.StartsWith("hello"); // false
startsIgnoreCase = text.ToLower().StartsWith("hello"); // true
.EndsWith(suffix)¶
Checks if string ends with suffix.
Signature:
Parameters:
suffix(string): Suffix to check
Returns: (boolean) True if ends with suffix, false otherwise
Examples:
text = "hello world";
endsWithWorld = text.EndsWith("world"); // true
endsWithHello = text.EndsWith("hello"); // false
// Check file extension
filename = "document.pdf";
isPdf = filename.EndsWith(".pdf"); // true
// Filter by suffix
files = allFiles.Filter((f) => f.name.EndsWith(".txt"));
// Domain check
email = "user@example.com";
isDotCom = email.EndsWith(".com"); // true
String Extraction¶
.Substring(startIndex)¶
Extracts substring from start index to end of string.
Signature:
Parameters:
startIndex(number): Zero-based starting position
Returns: (string) Substring from start index to end
Examples:
text = "Hello World";
sub = text.Substring(6); // "World"
// Extract after delimiter
email = "user@example.com";
atIndex = email.IndexOf("@");
domain = email.Substring(atIndex + 1); // "example.com"
// Get last characters
code = "ABC123";
lastThree = code.Substring(3); // "123"
// Empty if at end
text = "Test";
empty = text.Substring(4); // ""
.Substring(startIndex, length)¶
Extracts substring of specified length.
Signature:
Parameters:
startIndex(number): Zero-based starting positionlength(number): Number of characters to extract
Returns: (string) Substring of specified length
Examples:
text = "Hello World";
sub = text.Substring(0, 5); // "Hello"
mid = text.Substring(6, 5); // "World"
// Extract from middle
text = "2024-12-01";
year = text.Substring(0, 4); // "2024"
month = text.Substring(5, 2); // "12"
day = text.Substring(8, 2); // "01"
// Truncate with length
long = "This is a long string";
short = long.Substring(0, 10); // "This is a "
// Extract fixed-width fields
record = "JohnDoe 30 Developer";
name = record.Substring(0, 9).Trim(); // "JohnDoe"
age = record.Substring(9, 5).Trim(); // "30"
role = record.Substring(14, 9).Trim(); // "Developer"
// Zero length
text = "Test";
empty = text.Substring(2, 0); // ""
Common Patterns:
// Split filename and extension
filename = "document.pdf";
dotIndex = filename.LastIndexOf(".");
name = filename.Substring(0, dotIndex); // "document"
ext = filename.Substring(dotIndex + 1); // "pdf"
// Parse formatted string
data = "ABC:123:XYZ";
firstColon = data.IndexOf(":");
secondColon = data.IndexOf(":", firstColon + 1);
part1 = data.Substring(0, firstColon); // "ABC"
part2 = data.Substring(firstColon + 1, secondColon - firstColon - 1); // "123"
part3 = data.Substring(secondColon + 1); // "XYZ"
// Mask sensitive data
cardNumber = "1234567812345678";
masked = "****-****-****-" + cardNumber.Substring(12, 4); // "****-****-****-5678"
String Replacement¶
.Replace(oldValue, newValue)¶
Replaces all occurrences of a substring.
Signature:
Parameters:
oldValue(string): Text to replacenewValue(string): Replacement text
Returns: (string) Modified string
Examples:
text = "hello world";
replaced = text.Replace("world", "eversharp"); // "hello eversharp"
// Replace multiple occurrences
text = "foo bar foo baz";
result = text.Replace("foo", "qux"); // "qux bar qux baz"
// Remove by replacing with empty
text = "a-b-c";
clean = text.Replace("-", ""); // "abc"
// Format template
template = "Hello {name}, welcome to {company}";
message = template
.Replace("{name}", customerName)
.Replace("{company}", "Acme Insurance");
// Sanitize
dirty = "test@#$value";
clean = dirty.Replace("@", "").Replace("#", "").Replace("$", "");
Conversion¶
$ToString(value)¶
Converts any value to string.
Signature:
Parameters:
value(any): Value to convert
Returns: (string) String representation
Examples:
// Numbers
num = 42;
str = $ToString(num); // "42"
decimal = 3.14159;
strDecimal = $ToString(decimal); // "3.14159"
// Booleans
flag = true;
strFlag = $ToString(flag); // "True"
// Dates
date = $Now();
strDate = $ToString(date);
// Objects/arrays - implementation-specific
obj = { name: "Alice" };
strObj = $ToString(obj);
// Instance method
num = 100;
str = num.ToString(); // "100"
With Format (instance method):
// Format number
value = 1234.5678;
formatted = value.ToString("F2"); // "1234.57" (2 decimals)
// Format date
date = $Now();
formatted = date.ToString("yyyy-MM-dd"); // "2024-01-15"
Common Patterns¶
Pattern 1: Email Validation¶
function isValidEmail(email) {
if (email == null || email == "") {
return false;
}
email = email.Trim();
return (
email.Contains("@") &&
email.Contains(".") &&
email.IndexOf("@") < email.LastIndexOf(".")
);
}
Pattern 2: String Normalization¶
function normalizeString(input) {
if (input == null) {
return "";
}
return input.Trim().ToLower().Replace(" ", " "); // Remove double spaces
}
normalized = normalizeString(" HELLO WORLD ");
// "hello world"
Pattern 3: Parse CSV¶
csvLine = "John,Doe,30,Engineer";
fields = csvLine.Split(",");
firstName = fields[0]; // "John"
lastName = fields[1]; // "Doe"
age = $ToNumber(fields[2]); // 30
occupation = fields[3]; // "Engineer"
Pattern 4: String Builder¶
parts = [];
parts.Push("Hello");
parts.Push(" ");
parts.Push("World");
result = parts.Reduce((acc, x) => acc + x, "");
// "Hello World"
Pattern 5: Case-Insensitive Comparison¶
function equalsIgnoreCase(str1, str2) {
if (str1 == null || str2 == null) {
return str1 == str2;
}
return str1.ToLower() == str2.ToLower();
}
match = equalsIgnoreCase("Hello", "HELLO"); // true
Pattern 6: Extract Domain from Email¶
function getDomain(email) {
if (!email.Contains("@")) {
return null;
}
parts = email.Split("@");
return parts[1];
}
domain = getDomain("user@example.com"); // "example.com"
Pattern 7: Mask Sensitive Data¶
function maskEmail(email) {
if (!email.Contains("@")) {
return email;
}
parts = email.Split("@");
username = parts[0];
domain = parts[1];
if (username.Length <= 2) {
masked = username;
} else {
masked = username[0] + "***" + username[username.Length - 1];
}
return masked + "@" + domain;
}
masked = maskEmail("alice@example.com");
// "a***e@example.com"
Best Practices¶
1. Trim User Input¶
2. Normalize for Comparison¶
// Good
if (input.ToLower().Trim() == "yes") {
// Handles "YES", " yes ", "Yes", etc.
}
// Less flexible
if (input == "yes") {
// Only exact match
}
3. Check for Null/Empty¶
// Good
if (text != null && text.Trim() != "") {
// Process
}
// Risky
if (text != null) {
// May be whitespace-only
}
4. Chain String Operations¶
// Good
result = input.Trim().ToLower().Replace("-", "");
// More verbose
temp1 = input.Trim();
temp2 = temp1.ToLower();
result = temp2.Replace("-", "");
5. Validate Before Processing¶
// Good
if (email.Contains("@")) {
parts = email.Split("@");
// Use parts
}
// Risky
parts = email.Split("@"); // May not contain @
Advanced Examples¶
Example 1: Name Formatter¶
function formatName(firstName, lastName) {
if (firstName == null || lastName == null) {
return "";
}
first = firstName.Trim();
last = lastName.Trim();
if (first == "" || last == "") {
return "";
}
// Title case
firstUpper = first[0].ToUpper() + first.Substring(1).ToLower();
lastUpper = last[0].ToUpper() + last.Substring(1).ToLower();
return firstUpper + " " + lastUpper;
}
formatted = formatName("jOHN", "dOE");
// "John Doe"
Example 2: Parse Key-Value Pairs¶
function parseKeyValue(input) {
result = {};
lines = input.Split("\n");
lines.ForEach((line) => {
trimmed = line.Trim();
if (trimmed != "" && trimmed.Contains("=")) {
parts = trimmed.Split("=");
key = parts[0].Trim();
value = parts[1].Trim();
$SetValue(result, key, value);
}
});
return result;
}
config = parseKeyValue("name=Alice\nage=30\ncity=Springfield");
// { "name": "Alice", "age": "30", "city": "Springfield" }
Example 3: Text Statistics¶
function analyzeText(text) {
if (text == null || text == "") {
return null;
}
trimmed = text.Trim();
words = trimmed.Split(" ").Filter((w) => w != "");
return {
length: text.Length,
wordCount: words.Length,
hasUpperCase: text.ToUpper() != text.ToLower(),
hasNumbers:
text.Contains("0") ||
text.Contains("1") ||
text.Contains("2") ||
text.Contains("3") ||
text.Contains("4") ||
text.Contains("5") ||
text.Contains("6") ||
text.Contains("7") ||
text.Contains("8") ||
text.Contains("9"),
};
}
Performance Notes¶
- String operations create new strings (immutable)
- Chain operations to reduce intermediate variables
- Use
.Contains()before.Split()for validation - Case conversion is relatively expensive; cache if reused
Next Steps¶
-
Explore other categories:
- Conversion Functions
-
Learn related concepts:
-
See practical examples:
- Basic Calculations
- Business Rules