Search code examples
cstringc-strings

Swap specific text in string


I need to write a function swapLetters that receives two strings. The function transforms the string received as the first parameter by replacing the first character from the string that is passed as the second parameter with the last character from the same string, the second with the previous one, etc. to the middle of the string. If the second parameter contains an odd number of characters, nothing needs to be done with the character in the middle. If one of the parameters is an empty string, the function does not need to do anything.

For example:

char text[9]="dobar dan", letters[5]="abcde";

OUTPUT:

After transformation text is: 'doder den'

Explanation: first character in the string letters is "a", and in the string text, character "a" is replaced by the last character of string letters, which is "e". The second charater from string letters is "b", and in the string text, charater "b" is replaced by the penultimate character of string letters, which is "d", while with the letter "c "nothing has been done because it is in the middle of the string letters and there the function stops.

The function should return the cursor to the beginning of a text string for easier chain calling.

*Note: Auxiliary strings are not allowed

#include <stdio.h>
#include <string.h>
char *swapLetters(char *s1, char *s2) {
  int lenght1 = 0, lenght2 = 0;
  char *q1 = s1, *q2 = s2;
  while (*q1 != '\0') {
    lenght1++;
    q1++;
  }
  while (*q2 != '\0') {
    lenght2++;
    q2++;
  }
  return s1;
}

int main() {
  char text[9] = "dobar dan", letters[5] = "abcde";
  swapLetters(text, letters);
  printf("After transformation text is: '%s'\n", text);
  return 0;
}

Could you help me with this task? Strings are new to me.


Solution

  • As others have pointed, you are not providing enough space for your strings to have '\0' terminator.

    You need to change to:

    char text[10] = "dobar dan"; 
    char letters[6] = "abcde";
    

    But also, your function swapLetters is not swapping any characters:

    A correct function would have been:

    char *swapLetters(char *s1, char *s2) {
      int length2 = 0;
    
      char *q1 = s1, *q2 = s2;
    
      while (*q2 != '\0') {
        length2++;
        q2++;
      }
    
      while (*q1 != '\0') {
        // find the char in striong 'letters'
        for(int i=0; i<length2/2; i++){
            if(*q1 == s2[i]){
                *q1 = s2[length2-i-1];
            }
        }
        q1++;
      }
      
      return s1;
    }