Replace Character of String With Another Character N Place Down the Alphabet

Given a string ‘s’ and a number ‘n’, write a function that returns a string with each character in s replaced with another character that is ‘n’ positions down the alphabet.

If n is 1, A is replaced with B, B is replaced with C, Z is replaced with A and so on.

If n is 2, A is replaced with C, B is replaced with D, Z is replaced with B and so on.

Algorithm

  • Convert the received value n = n % 26.
  • Iterate through each character of the string.
  • For each character in string.
    • Add n to ASCII value of character and save it (say “ch”).
    • If character is greater than ‘Z’ then
      • Find the value by which character is ahead ‘Z’.
      • Final character value should be ‘A’ + (value – 1)

Let’s analyze the full program which solves the above problem.

#include <stdio.h>
#include <string.h>
#include <stdint.h>

void string_encoding (char *input, uint32_t n)
{
	if (n == 0)
		return;
	if (n > 26)
	{
		n = n % 26;
	}
	int size = strlen (input);
	for (int i = 0; i < size; i++)
	{
		input[i] = input[i] + n;
		if (input[i] > 'Z')
		{
			input[i] = input[i] - ('Z' + 1) + 'A';
		}
	}
}

int main ()
{
	char input[100];
	uint32_t n;
	printf ("Enter Input String \n");
	scanf ("%s", input);
	printf ("Enter position \n");
	scanf ("%u", &n);
	printf ("Input String: %s \n", input);
	string_encoding (input, n);
	printf ("Modified String: %s \n", input);
}

Let’s analyze output of the above function.

Enter Input String 
ABC
Enter position 
1
Input String: ABC 
Modified String: BCD 
----------------------------------------------------------
Enter Input String 
ABC
Enter position 
0
Input String: ABC 
Modified String: ABC 
-----------------------------------------------------------
Enter Input String 
ABC
Enter position 
25
Input String: ABC 
Modified String: ZAB

Leave a Reply

Your email address will not be published. Required fields are marked *