Added x_string utility functions
Added implementation for string length Added implementation for string copy Added implementation for string concatination
This commit is contained in:
parent
8ee3a304bb
commit
82fd8556ab
60
x_string/x_string.c
Normal file
60
x_string/x_string.c
Normal file
@ -0,0 +1,60 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int x_strlen(char* str){
|
||||
char* ptr = str;
|
||||
while(*ptr != '\0'){
|
||||
ptr++;
|
||||
}
|
||||
return ptr - str;
|
||||
}
|
||||
|
||||
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++;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
int main(){
|
||||
|
||||
char x[] = "hlo";
|
||||
char y[] = "world";
|
||||
|
||||
//printf("%d\n", x_strlen(x));
|
||||
//printf("%d\n", x_strlen(x));
|
||||
|
||||
char* z = x_strconcat(x,y);
|
||||
|
||||
puts(z);
|
||||
|
||||
//free(z);
|
||||
|
||||
return 0;
|
||||
}
|
8
x_string/x_string.h
Normal file
8
x_string/x_string.h
Normal file
@ -0,0 +1,8 @@
|
||||
#ifndef X_STRING_H
|
||||
#define X_STRING_H
|
||||
|
||||
int x_strlen(char*);
|
||||
void x_strcpy(char*, char*, const int);
|
||||
char* x_strconcat(char*, char*);
|
||||
|
||||
#endif
|
Loading…
Reference in New Issue
Block a user