Advertisement
dmilicev

swap_strings_v2.c

Apr 25th, 2020
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.59 KB | None | 0 0
  1. /*
  2.  
  3.     swap_strings_v2.c
  4.  
  5.     https://web.facebook.com/groups/c.programing/permalink/1558823557609822/
  6.  
  7.     A string consists of two strings separated by ';' .
  8.     The task is to change the order of the two stings.
  9.  
  10.     Version without string.h .
  11.  
  12.  
  13.     You can find all my C programs at Dragan Milicev's pastebin:
  14.  
  15.     https://pastebin.com/u/dmilicev
  16.  
  17. */
  18.  
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21.  
  22. char *swap(char s[] )
  23. {
  24.     int i, j, length;
  25.     char delimiter = ';';
  26.  
  27.     i=0;                                        // calculate length of s, implementation of strlen()
  28.     length=0;
  29.     while( s[i] != '\0' )
  30.     {
  31.         length++;
  32.         i++;
  33.     }
  34.  
  35.     char tmp[length+1], first[length+1], second[length+1];  // declare 3 strings
  36.  
  37.     i=0;                                        // get first string from string s
  38.     j=0;
  39.     while( s[i] != delimiter )
  40.     {
  41.         first[j] = s[i];
  42.         i++;
  43.         j++;
  44.     }
  45.     first[j] = '\0';                            // finish string first
  46.  
  47.     i++;                                        // get second string from string s
  48.     j=0;
  49.     while( s[i] != '\0')
  50.     {
  51.         second[j] = s[i];
  52.         i++;
  53.         j++;
  54.     }
  55.     second[j] = '\0';                           // finish string second
  56.  
  57.     i=0;                                        // put second string in string s
  58.     j=0;
  59.     while( second[i] != '\0')
  60.     {
  61.         s[j] = second[i];
  62.         i++;
  63.         j++;
  64.     }
  65.  
  66.     s[j] = delimiter;                           // put delimiter in string s
  67.  
  68.     i=0;                                        // put first string in string s
  69.     j++;
  70.     while( first[i] != '\0')
  71.     {
  72.         s[j] = first[i];
  73.         i++;
  74.         j++;
  75.     }
  76.     s[j] = '\0';                                // finish string s
  77.  
  78.     return s;
  79. }
  80.  
  81.  
  82. int main(void)
  83. {
  84.     char str[] = "first;second";
  85.  
  86.     printf("\n before: |%s| \n", str );
  87.  
  88.     swap(str);
  89.  
  90.     printf("\n after:  |%s| \n", str );
  91.  
  92.     printf("\n again:  |%s| \n", swap(str) );
  93.  
  94.  
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement