Alignment Techniques
#include <stdio.h>
int main() {
// Left alignment
printf("%-10s", "Hello"); // Left-aligned in 10 characters
// Right alignment
printf("%10s", "World"); // Right-aligned in 10 characters
// Centered alignment (manual method)
printf("%*s%s%*s",
(10 - strlen("Linux"))/2, "",
"Linux",
(10 - strlen("Linux"))/2, "");
return 0;
}
2. String Manipulation Techniques
#include <string.h>
char* left_align(char* str, int width) {
static char buffer[100];
snprintf(buffer, sizeof(buffer), "%-*s", width, str);
return buffer;
}
char* right_align(char* str, int width) {
static char buffer[100];
snprintf(buffer, sizeof(buffer), "%*s", width, str);
return buffer;
}
Advanced Alignment Strategies
Alignment Method Comparison
Method |
Pros |
Cons |
Printf |
Built-in |
Limited flexibility |
Custom Functions |
Highly customizable |
More complex |
String Manipulation |
Precise control |
Performance overhead |
Alignment Workflow
graph TD
A[Input Text] --> B{Alignment Type}
B --> |Left| C[Left-Align Function]
B --> |Right| D[Right-Align Function]
B --> |Center| E[Center-Align Function]
C --> F[Formatted Output]
D --> F
E --> F
- Use fixed-width buffers
- Minimize memory allocations
- Leverage built-in formatting when possible
#include <stdio.h>
void format_log_entry(const char* timestamp,
const char* level,
const char* message) {
printf("[%-20s] [%5s] %s\n",
timestamp,
level,
message);
}
int main() {
format_log_entry("2023-06-15 10:30:45",
"INFO",
"System initialized");
return 0;
}
Best Practices
- Choose appropriate alignment method
- Consider readability
- Optimize for performance
- Use consistent formatting
At LabEx, we emphasize clean and efficient text manipulation techniques in system programming.