Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- swap_strings_v3.c
- https://web.facebook.com/groups/c.programing/permalink/1558823557609822/
- A string consists of two strings separated by ';' .
- The task is to change the order of the two stings.
- Version with pointers and without string.h .
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- #include <stdlib.h>
- char *swap(char *s)
- {
- int i, j, length;
- char *tmp, *first, *second;
- char delimiter = ';';
- i=0; // calculate length of s, implementation of strlen()
- length=0;
- while( *(s+i) != '\0' )
- {
- length++;
- i++;
- }
- tmp = (char *)malloc( length + 1 ); // reserve memory for tmp, + 1 for '\0'
- if(tmp == NULL) // checking that it is successful
- {
- printf("\n malloc error for tmp ! \n");
- exit(1);
- }
- first = (char *)malloc( length + 1 ); // reserve memory for first, + 1 for '\0'
- if(first == NULL) // checking that it is successful
- {
- printf("\n malloc error for first ! \n");
- exit(1);
- }
- second = (char *)malloc( length + 1 ); // reserve memory for second, + 1 for '\0'
- if(second == NULL) // checking that it is successful
- {
- printf("\n malloc error for second ! \n");
- exit(1);
- }
- i=0; // get first string from string s
- j=0;
- while( *(s+i) != delimiter )
- {
- *(first+j) = *(s+i);
- i++;
- j++;
- }
- *(first+j) = '\0'; // finish string first
- i++; // get second string from string s
- j=0;
- while( *(s+i) != '\0')
- {
- *(second+j) = *(s+i);
- i++;
- j++;
- }
- *(second+j) = '\0'; // finish string second
- i=0; // put second string in string s
- j=0;
- while( *(second+i) != '\0')
- {
- *(s+j) = *(second+i);
- i++;
- j++;
- }
- *(s+j) = delimiter; // put delimiter in string s
- i=0; // put first string in string s
- j++;
- while( *(first+i) != '\0')
- {
- *(s+j) = *(first+i);
- i++;
- j++;
- }
- *(s+j) = '\0'; // finish string s
- return s;
- }
- int main(void)
- {
- char str[] = "first;second";
- printf("\n before: |%s| \n", str );
- swap(str);
- printf("\n after: |%s| \n", str );
- printf("\n again: |%s| \n", swap(str) );
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement