72 lines
1.3 KiB
C
72 lines
1.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
// return the length of string to the null terminator
|
|
int x_strlen(char* str){
|
|
char* ptr = str;
|
|
while(*ptr != '\0'){
|
|
ptr++;
|
|
}
|
|
return ptr - str;
|
|
}
|
|
|
|
// copy one string to another destination
|
|
// must include the size of the destination
|
|
void x_strcpy(char* dest, char* src, const int size_dest){
|
|
char* dest_ptr = dest;
|
|
char* src_ptr = src;
|
|
int i = 0;
|
|
|
|
while(*src_ptr != '\0'){
|
|
if (i >= size_dest){
|
|
fprintf(stderr, "Error: x_strcpy\nSource string exeeds destination memory\n");
|
|
exit(1);
|
|
}
|
|
*dest_ptr = *src_ptr;
|
|
dest_ptr++;
|
|
src_ptr++;
|
|
i++;
|
|
}
|
|
|
|
}
|
|
// compare two strings
|
|
// return 0 if equal to eachother
|
|
// return -1 if not
|
|
int x_strcmp (char* str1, char* str2){
|
|
char* ptr1 = str1;
|
|
char* ptr2 = str2;
|
|
|
|
while(*ptr1 != '\0' && *ptr2 != '\0'){
|
|
if(*ptr1 != *ptr2){
|
|
return -1;
|
|
}
|
|
|
|
ptr1++;
|
|
ptr2++;
|
|
}
|
|
|
|
// if havent reached the end of one of the strings
|
|
if (*ptr1 != '\0' || *ptr2 != '\0'){
|
|
return -1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
// concatinate two strings
|
|
char* x_strconcat(char* str1, char* str2){
|
|
|
|
char* new_string;
|
|
|
|
int len1 = x_strlen(str1);
|
|
int len2 = x_strlen(str2);
|
|
int new_length = len1 + len2;
|
|
|
|
new_string = malloc( sizeof(*new_string) * new_length );
|
|
x_strcpy(new_string, str1, new_length);
|
|
x_strcpy(&new_string[len1], str2, new_length - len1);
|
|
|
|
return new_string;
|
|
}
|