Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- #include <Windows.h>
- typedef struct{
- unsigned int size;
- char * text;
- }String;
- //Let the user input a string
- String * ReadString(int max_size);
- //Test print a string
- void PrintString(String * text);
- //Use this for strings instead of free
- void FreeString(String * string);
- //Create a string
- String * CreateString(const char * text);
- String * CreateString(const char * text){
- String * ret = (String*)malloc(sizeof(String));
- if (ret == NULL)
- return NULL;
- ret->size = strlen(text)+1;
- ret->text = (char*)malloc(ret->size);
- if (ret->text != NULL)
- strcpy(ret->text, text);
- else{
- free(ret);
- return NULL;
- }
- return ret;
- }
- void FreeString(String * string){
- if (string != NULL){
- //Free the pointer inside the struct first if its not null
- if (string->text != NULL)
- free(string->text);
- //free the rest of the struct
- free(string);
- }
- }
- void PrintString(String * text){
- if (text == NULL)
- printf("String is empty!");
- else
- printf("Size (in bytes): %u\nData: %s\n",text->size,text->text);
- }
- String * ReadString(int max_size){
- char * buffer = (char*)malloc(max_size);
- String * ret;
- if (buffer == NULL)
- return NULL;
- fgets(buffer, max_size, stdin);
- //strip endline
- buffer[strlen(buffer) - 1] = NULL;
- ret = CreateString(buffer);
- free(buffer);
- return ret;
- }
- void main(){
- //Using the string raw:
- String Terrah;
- String * Kluffu;
- String * First;
- String * Last;
- char * split;
- char temp;
- Terrah.text = "Hello this is Terrah";
- Terrah.size = strlen(Terrah.text) + 1;
- PrintString(&Terrah);
- //Here you'd normally free the data, but since this is compiled in the compilier
- //we'd crash if we tried to deallocate this memory
- //FreeString(&Terrah);
- //We never do this for non pointers
- //dynamically
- printf("First and last name?: ");
- Kluffu = ReadString(100);
- PrintString(Kluffu);
- //Split the name
- //find the space
- //strstr returns null if it didnt find the substring or a pointer to the begining of it
- split = strstr(Kluffu->text," ");
- //Split if we found it
- if (split != NULL){
- //temporarily null terminate
- temp = split[0];
- split[0] = NULL;
- First = CreateString(Kluffu->text);
- Last = CreateString(split+1);
- //Restore
- split[0] = temp;
- PrintString(First);
- PrintString(Last);
- //Delete
- FreeString(First);
- FreeString(Last);
- First = NULL;
- Last = NULL;
- }
- //If you wanted to get info out of the string here, you'd use sscanf
- //like you would scanf but with the text buffer as the first argument
- //sscanf(Kluffu->text, "", "");
- FreeString(Kluffu);
- _getch();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement