# String Library (strlib)
# Difficulty: 1
# Description: Examples of using the String Library in Razen
## Introduction
The String Library (`strlib`) provides essential functions for working with strings in Razen. This library helps you manipulate and process text data efficiently with operations like case conversion, substring extraction, string replacement, and more.
## Library Overview
### String Library Functions
- `upper` → Converts a string to uppercase
- `lower` → Converts a string to lowercase
- `substring` → Extracts a portion of a string
- `replace` → Replaces occurrences of a substring
- `length` → Returns the length of a string
- `split` → Splits a string into an array using a delimiter
- `trim` → Removes whitespace from both ends of a string
- `starts_with` → Checks if a string starts with a specified prefix
- `ends_with` → Checks if a string ends with a specified suffix
- `contains` → Checks if a string contains a substring
- `repeat` → Repeats a string a specified number of times
## How to Use the String Library
### Library Import
To use the String Library in Razen, you first need to import it using the `lib` keyword:
```razen
lib strlib;
```
### Function Calling
Once imported, you can call functions from the library using the double colon `::` syntax:
```razen
strlib::functionName(parameters);
```
**Note about bracket notation (Legacy):**
In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions:
```razen
# DEPRECATED - Only works in Razen before beta v0.1.75
strlib[functionName](parameters);
```
This syntax is no longer supported in newer versions of Razen.
## Basic Examples
### Using the upper and lower Functions
```razen
# Convert string to uppercase
str greeting = "Hello, Razen!";
str upperGreeting = strlib::upper(greeting);
show upperGreeting; # Output: "HELLO, RAZEN!"
# Convert string to lowercase
str lowerGreeting = strlib::lower(greeting);
show lowerGreeting; # Output: "hello, razen!"
```
### Using the substring Function
```razen
str text = "Hello, Razen Programming Language!";
# Get substring from index 7 to end
str sub1 = strlib::substring(text, 7);
show sub1; # Output: "Razen Programming Language!"
# Get substring from index 7 to 12 (exclusive)
str sub2 = strlib::substring(text, 7, 12);
show sub2; # Output: "Razen"
# Negative index counts from the end
str sub3 = strlib::substring(text, -9);
show sub3; # Output: "Language!"
```
### Using the replace Function
```razen
str message = "I love apples and apples are tasty";
# Replace first occurrence
str newMessage = strlib::replace(message, "apples", "oranges");
show newMessage; # Output: "I love oranges and apples are tasty"
# Replace all occurrences
str finalMessage = strlib::replace(message, "apples", "oranges", true);
show finalMessage; # Output: "I love oranges and oranges are tasty"
```
### Using the length Function
```razen
str name = "Razen";
num nameLength = strlib::length(name);
show "The length of '" + name + "' is " + nameLength; # Output: "The length of 'Razen' is 5"
# Works with empty strings
show strlib::length(""); # Output: 0
```
### Using the split Function
```razen
str csv = "apple,banana,orange,grape";
str fruits = strlib::split(csv, ",");
show fruits; # Output: ["apple", "banana", "orange", "grape"]
# Split with limit
str limitedSplit = strlib::split("one two three four five", " ", 3);
show limitedSplit; # Output: ["one", "two", "three four five"]
```
### Using the trim Function
```razen
str padded = " Hello, Razen! ";
str trimmed = strlib::trim(padded);
show "|" + trimmed + "|"; # Output: "|Hello, Razen!|"
# Also works with other whitespace characters
str messy = "\t\n Clean me up! \r\n";
show "|" + strlib::trim(messy) + "|"; # Output: "|Clean me up!|"
```
### Using the starts_with and ends_with Functions
```razen
str filename = "document.txt";
# Check if string starts with a prefix
bool isDocument = strlib::starts_with(filename, "doc");
show "Starts with 'doc': " + isDocument; # Output: true
# Check if string ends with a suffix
bool isTxt = strlib::ends_with(filename, ".txt");
show "Ends with '.txt': " + isTxt; # Output: true
```
### Using the contains Function
```razen
str sentence = "The quick brown fox jumps over the lazy dog";
# Check if string contains a substring
bool hasFox = strlib::contains(sentence, "fox");
show "Contains 'fox': " + hasFox; # Output: true
# Case-sensitive check
bool hasQuick = strlib::contains(sentence, "QUICK");
show "Contains 'QUICK': " + hasQuick; # Output: false
```
### Using the repeat Function
```razen
# Repeat a string
str repeated = strlib::repeat("ha", 3);
show repeated; # Output: "hahaha"
# Edge cases
show strlib::repeat("test", 0); # Output: ""
show strlib::repeat("a", 5); # Output: "aaaaa"
```
## Advanced Examples
### String Manipulation Function
```razen
# Function to convert string to title case
fun toTitleCase(str text) {
if (strlib::length(text) == 0) {
return "";
}
# Split into words
str words = strlib::split(text, " ");
str result = "";
# Capitalize first letter of each word
for (num i = 0; i < strlib::length(words); i = i + 1) {
if (strlib::length(words[i]) > 0) {
str firstChar = strlib::upper(strlib::substring(words[i], 0, 1));
str rest = strlib::lower(strlib::substring(words[i], 1));
if (i > 0) {
result = result + " ";
}
result = result + firstChar + rest;
}
}
return result;
}
# Test the function
str title = toTitleCase("the quick brown fox");
show title; # Output: "The Quick Brown Fox"
```
### String Validation Function
```razen
# Function to validate an email address
fun isValidEmail(str email) {
# Basic email validation
if (strlib::length(email) == 0) {
return false;
}
# Check for @ symbol
if (!strlib::contains(email, "@")) {
return false;
}
# Split into local and domain parts
str parts = strlib::split(email, "@");
if (strlib::length(parts) != 2) {
return false;
}
str localPart = parts[0];
str domain = parts[1];
# Validate local part and domain
if (strlib::length(localPart) == 0 || strlib::length(domain) == 0) {
return false;
}
# Check domain has a dot
if (!strlib::contains(domain, ".")) {
return false;
}
return true;
}
# Test the function
show isValidEmail("user@example.com"); # true
show isValidEmail("invalid-email"); # false
show isValidEmail("user@domain"); # false
show isValidEmail("@domain.com"); # false
```
### String Formatting Function
```razen
# Function to format a phone number
fun formatPhoneNumber(str input) {
# Remove all non-digit characters
str digits = "";
for (num i = 0; i < strlib::length(input); i = i + 1) {
str c = strlib::substring(input, i, i + 1);
if (strlib::contains("0123456789", c)) {
digits = digits + c;
}
}
# Format as (XXX) XXX-XXXX
if (strlib::length(digits) == 10) {
str part1 = strlib::substring(digits, 0, 3);
str part2 = strlib::substring(digits, 3, 6);
str part3 = strlib::substring(digits, 6);
return "(" + part1 + ") " + part2 + "-" + part3;
}
# Return original if not 10 digits
return input;
}
# Test the function
show formatPhoneNumber("1234567890"); # (123) 456-7890
show formatPhoneNumber("123-456-7890"); # (123) 456-7890
show formatPhoneNumber("(123) 456-7890"); # (123) 456-7890
show formatPhoneNumber("12345"); # 12345 (unchanged)
```
## Practical Application: Text Analyzer
```razen
# Simple text analyzer using string functions
fun analyzeText(str text) {
show "=== Text Analysis ===";
# Basic statistics
num charCount = strlib::length(text);
num wordCount = 0;
num sentenceCount = 0;
# Count words and sentences
if (charCount > 0) {
str words = strlib::split(text, " ");
wordCount = strlib::length(words);
# Simple sentence counting (count periods, question marks, and exclamation points)
sentenceCount = strlib::length(strlib::split(text, "[.!?]+"));
}
# Show statistics
show "Character count: " + charCount;
show "Word count: " + wordCount;
show "Sentence count: " + sentenceCount;
# Calculate average word length
if (wordCount > 0) {
num totalLetters = 0;
str words = strlib::split(text, " ");
for (num i = 0; i < strlib::length(words); i = i + 1) {
totalLetters = totalLetters + strlib::length(words[i]);
}
num avgWordLength = totalLetters / wordCount;
show "Average word length: " + avgWordLength + " characters";
}
# Most common words (simplified)
if (wordCount > 0) {
show "\nMost common words (top 5):";
str words = strlib::split(strlib::lower(text), " ");
map wordCounts = {};
# Count word frequencies
for (num i = 0; i < strlib::length(words); i = i + 1) {
str word = words[i];
if (strlib::length(word) > 0) {
if (wordCounts[word] == null) {
wordCounts[word] = 1;
} else {
wordCounts[word] = wordCounts[word] + 1;
}
}
}
# Sort by frequency (simplified)
# Note: In a real implementation, you'd want a proper sorting function
num count = 0;
for (key in wordCounts) {
if (count < 5) {
show "- " + key + ": " + wordCounts[key] + " times";
count = count + 1;
}
}
}
}
# Test the text analyzer
str sampleText = "Hello! This is a test. This is only a test. Testing the text analyzer function. Hello again!";
analyzeText(sampleText);
```
## Summary
The String Library in Razen provides powerful functions for text processing:
- `upper` and `lower` for case conversion
- `substring` for extracting parts of strings
- `replace` for text substitution
- `length` to get string length
- `split` to break strings into arrays
- `trim` to remove whitespace
- `starts_with` and `ends_with` for prefix/suffix checking
- `contains` for substring search
- `repeat` for string repetition
These functions help you work with text data efficiently in your Razen programs.
# String Library (strlib)
# Difficulty: 1
# Description: Examples of using the String Library in Razen
## Introduction
The String Library (`strlib`) provides essential functions for working with strings in Razen. This library helps you manipulate and process text data efficiently with operations like case conversion, substring extraction, string replacement, and more.
## Library Overview
### String Library Functions
- `upper` → Converts a string to uppercase
- `lower` → Converts a string to lowercase
- `substring` → Extracts a portion of a string
- `replace` → Replaces occurrences of a substring
- `length` → Returns the length of a string
- `split` → Splits a string into an array using a delimiter
- `trim` → Removes whitespace from both ends of a string
- `starts_with` → Checks if a string starts with a specified prefix
- `ends_with` → Checks if a string ends with a specified suffix
- `contains` → Checks if a string contains a substring
- `repeat` → Repeats a string a specified number of times
## How to Use the String Library
### Library Import
To use the String Library in Razen, you first need to import it using the `lib` keyword:
```razen
lib strlib;
```
### Function Calling
Once imported, you can call functions from the library using the double colon `::` syntax:
```razen
strlib::functionName(parameters);
```
**Note about bracket notation (Legacy):**
In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions:
```razen
# DEPRECATED - Only works in Razen before beta v0.1.75
strlib[functionName](parameters);
```
This syntax is no longer supported in newer versions of Razen.
## Basic Examples
### Using the upper and lower Functions
```razen
# Convert string to uppercase
str greeting = "Hello, Razen!";
str upperGreeting = strlib::upper(greeting);
show upperGreeting; # Output: "HELLO, RAZEN!"
# Convert string to lowercase
str lowerGreeting = strlib::lower(greeting);
show lowerGreeting; # Output: "hello, razen!"
```
### Using the substring Function
```razen
str text = "Hello, Razen Programming Language!";
# Get substring from index 7 to end
str sub1 = strlib::substring(text, 7);
show sub1; # Output: "Razen Programming Language!"
# Get substring from index 7 to 12 (exclusive)
str sub2 = strlib::substring(text, 7, 12);
show sub2; # Output: "Razen"
# Negative index counts from the end
str sub3 = strlib::substring(text, -9);
show sub3; # Output: "Language!"
```
### Using the replace Function
```razen
str message = "I love apples and apples are tasty";
# Replace first occurrence
str newMessage = strlib::replace(message, "apples", "oranges");
show newMessage; # Output: "I love oranges and apples are tasty"
# Replace all occurrences
str finalMessage = strlib::replace(message, "apples", "oranges", true);
show finalMessage; # Output: "I love oranges and oranges are tasty"
```
### Using the length Function
```razen
str name = "Razen";
num nameLength = strlib::length(name);
show "The length of '" + name + "' is " + nameLength; # Output: "The length of 'Razen' is 5"
# Works with empty strings
show strlib::length(""); # Output: 0
```
### Using the split Function
```razen
str csv = "apple,banana,orange,grape";
str fruits = strlib::split(csv, ",");
show fruits; # Output: ["apple", "banana", "orange", "grape"]
# Split with limit
str limitedSplit = strlib::split("one two three four five", " ", 3);
show limitedSplit; # Output: ["one", "two", "three four five"]
```
### Using the trim Function
```razen
str padded = " Hello, Razen! ";
str trimmed = strlib::trim(padded);
show "|" + trimmed + "|"; # Output: "|Hello, Razen!|"
# Also works with other whitespace characters
str messy = "\t\n Clean me up! \r\n";
show "|" + strlib::trim(messy) + "|"; # Output: "|Clean me up!|"
```
### Using the starts_with and ends_with Functions
```razen
str filename = "document.txt";
# Check if string starts with a prefix
bool isDocument = strlib::starts_with(filename, "doc");
show "Starts with 'doc': " + isDocument; # Output: true
# Check if string ends with a suffix
bool isTxt = strlib::ends_with(filename, ".txt");
show "Ends with '.txt': " + isTxt; # Output: true
```
### Using the contains Function
```razen
str sentence = "The quick brown fox jumps over the lazy dog";
# Check if string contains a substring
bool hasFox = strlib::contains(sentence, "fox");
show "Contains 'fox': " + hasFox; # Output: true
# Case-sensitive check
bool hasQuick = strlib::contains(sentence, "QUICK");
show "Contains 'QUICK': " + hasQuick; # Output: false
```
### Using the repeat Function
```razen
# Repeat a string
str repeated = strlib::repeat("ha", 3);
show repeated; # Output: "hahaha"
# Edge cases
show strlib::repeat("test", 0); # Output: ""
show strlib::repeat("a", 5); # Output: "aaaaa"
```
## Advanced Examples
### String Manipulation Function
```razen
# Function to convert string to title case
fun toTitleCase(str text) {
if (strlib::length(text) == 0) {
return "";
}
# Split into words
str words = strlib::split(text, " ");
str result = "";
# Capitalize first letter of each word
for (num i = 0; i < strlib::length(words); i = i + 1) {
if (strlib::length(words[i]) > 0) {
str firstChar = strlib::upper(strlib::substring(words[i], 0, 1));
str rest = strlib::lower(strlib::substring(words[i], 1));
if (i > 0) {
result = result + " ";
}
result = result + firstChar + rest;
}
}
return result;
}
# Test the function
str title = toTitleCase("the quick brown fox");
show title; # Output: "The Quick Brown Fox"
```
### String Validation Function
```razen
# Function to validate an email address
fun isValidEmail(str email) {
# Basic email validation
if (strlib::length(email) == 0) {
return false;
}
# Check for @ symbol
if (!strlib::contains(email, "@")) {
return false;
}
# Split into local and domain parts
str parts = strlib::split(email, "@");
if (strlib::length(parts) != 2) {
return false;
}
str localPart = parts[0];
str domain = parts[1];
# Validate local part and domain
if (strlib::length(localPart) == 0 || strlib::length(domain) == 0) {
return false;
}
# Check domain has a dot
if (!strlib::contains(domain, ".")) {
return false;
}
return true;
}
# Test the function
show isValidEmail("user@example.com"); # true
show isValidEmail("invalid-email"); # false
show isValidEmail("user@domain"); # false
show isValidEmail("@domain.com"); # false
```
### String Formatting Function
```razen
# Function to format a phone number
fun formatPhoneNumber(str input) {
# Remove all non-digit characters
str digits = "";
for (num i = 0; i < strlib::length(input); i = i + 1) {
str c = strlib::substring(input, i, i + 1);
if (strlib::contains("0123456789", c)) {
digits = digits + c;
}
}
# Format as (XXX) XXX-XXXX
if (strlib::length(digits) == 10) {
str part1 = strlib::substring(digits, 0, 3);
str part2 = strlib::substring(digits, 3, 6);
str part3 = strlib::substring(digits, 6);
return "(" + part1 + ") " + part2 + "-" + part3;
}
# Return original if not 10 digits
return input;
}
# Test the function
show formatPhoneNumber("1234567890"); # (123) 456-7890
show formatPhoneNumber("123-456-7890"); # (123) 456-7890
show formatPhoneNumber("(123) 456-7890"); # (123) 456-7890
show formatPhoneNumber("12345"); # 12345 (unchanged)
```
## Practical Application: Text Analyzer
```razen
# Simple text analyzer using string functions
fun analyzeText(str text) {
show "=== Text Analysis ===";
# Basic statistics
num charCount = strlib::length(text);
num wordCount = 0;
num sentenceCount = 0;
# Count words and sentences
if (charCount > 0) {
str words = strlib::split(text, " ");
wordCount = strlib::length(words);
# Simple sentence counting (count periods, question marks, and exclamation points)
sentenceCount = strlib::length(strlib::split(text, "[.!?]+"));
}
# Show statistics
show "Character count: " + charCount;
show "Word count: " + wordCount;
show "Sentence count: " + sentenceCount;
# Calculate average word length
if (wordCount > 0) {
num totalLetters = 0;
str words = strlib::split(text, " ");
for (num i = 0; i < strlib::length(words); i = i + 1) {
totalLetters = totalLetters + strlib::length(words[i]);
}
num avgWordLength = totalLetters / wordCount;
show "Average word length: " + avgWordLength + " characters";
}
# Most common words (simplified)
if (wordCount > 0) {
show "\nMost common words (top 5):";
str words = strlib::split(strlib::lower(text), " ");
map wordCounts = {};
# Count word frequencies
for (num i = 0; i < strlib::length(words); i = i + 1) {
str word = words[i];
if (strlib::length(word) > 0) {
if (wordCounts[word] == null) {
wordCounts[word] = 1;
} else {
wordCounts[word] = wordCounts[word] + 1;
}
}
}
# Sort by frequency (simplified)
# Note: In a real implementation, you'd want a proper sorting function
num count = 0;
for (key in wordCounts) {
if (count < 5) {
show "- " + key + ": " + wordCounts[key] + " times";
count = count + 1;
}
}
}
}
# Test the text analyzer
str sampleText = "Hello! This is a test. This is only a test. Testing the text analyzer function. Hello again!";
analyzeText(sampleText);
```
## Summary
The String Library in Razen provides powerful functions for text processing:
- `upper` and `lower` for case conversion
- `substring` for extracting parts of strings
- `replace` for text substitution
- `length` to get string length
- `split` to break strings into arrays
- `trim` to remove whitespace
- `starts_with` and `ends_with` for prefix/suffix checking
- `contains` for substring search
- `repeat` for string repetition
These functions help you work with text data efficiently in your Razen programs.