String Manipulation
Regular Expression Handling
package main
import (
"regexp"
"fmt"
)
func main() {
// Regex pattern matching
pattern := regexp.MustCompile(`\d+`)
text := "LabEx Tutorial 2023"
matches := pattern.FindAllString(text, -1)
}
String Builder for Efficient Manipulation
graph LR
A[strings.Builder] --> B[Efficient Concatenation]
B --> C[Low Memory Allocation]
B --> D[High Performance]
func efficientConcatenation() string {
var builder strings.Builder
for i := 0; i < 1000; i++ {
builder.WriteString("Golang")
}
return builder.String()
}
Parsing and Conversion
Conversion Type |
Method |
Example |
String to Int |
strconv.Atoi() |
num, _ := strconv.Atoi("123") |
Int to String |
strconv.Itoa() |
str := strconv.Itoa(456) |
String to Float |
strconv.ParseFloat() |
float, _ := strconv.ParseFloat("3.14", 64) |
Advanced Manipulation Techniques
// Replacing with Regex
func replaceWithRegex(text string) string {
regex := regexp.MustCompile(`\s+`)
return regex.ReplaceAllString(text, "-")
}
// Custom String Transformation
func transformString(input string) string {
return strings.Map(func(r rune) rune {
if unicode.IsLower(r) {
return unicode.ToUpper(r)
}
return r
}, input)
}
Unicode Manipulation
// Handling Unicode Characters
func unicodeManipulation() {
text := "Golang ๐"
// Count runes instead of bytes
runeCount := utf8.RuneCountInString(text)
// Iterate over runes
for _, runeValue := range text {
fmt.Printf("%c ", runeValue)
}
}
String Validation Patterns
// Email Validation Example
func isValidEmail(email string) bool {
emailRegex := regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
return emailRegex.MatchString(email)
}
graph TD
A[String Manipulation] --> B[Use strings.Builder]
A --> C[Minimize Allocations]
A --> D[Prefer Rune-based Operations]
A --> E[Avoid Repeated Concatenations]
// Multi-step String Processing
func processString(input string) string {
// Trim spaces
trimmed := strings.TrimSpace(input)
// Replace multiple spaces
normalized := regexp.MustCompile(`\s+`).ReplaceAllString(trimmed, " ")
// Convert to title case
return strings.Title(normalized)
}
Memory Management Considerations
Technique |
Memory Impact |
Performance |
strings.Builder |
Low Allocation |
High |
+ Operator |
High Allocation |
Low |
fmt.Sprintf |
Moderate Allocation |
Moderate |