Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- swap_strings_v2.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 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 delimiter = ';';
- i=0; // calculate length of s, implementation of strlen()
- length=0;
- while( s[i] != '\0' )
- {
- length++;
- i++;
- }
- char tmp[length+1], first[length+1], second[length+1]; // declare 3 strings
- 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