+ 1

replacing all string characters with new characters

Hello everyone, would anyone have an idea of how to loop through a string and replace the characters of that string with a new set of characters? For instance, if I wanted to change the characters in, string letters_1 = "abcdef", with the characters in, string letters_2 = "zxcvbn" to have "letters_1" print "zxcvbn" instead of "abcdef". I've tried multiple different ways, but can't seem to get how to loop through both strings and change "abcdef" to "qufhte. below, I need to loop through "plaintext" and change those characters with argv[1] characters. Also just as a note, I'm using the cs50 library. That's why I can use "string" and "get_string" Any help is appropriate. Thank you! https://code.sololearn.com/c6a20A14a6A2

14th Apr 2021, 9:13 PM
David
David - avatar
3 ответов
+ 2
Does this clear it up? I don't know what is in your cs50.h library so I didn't rely on get_string or string. It looks like string is basically "char *" but you'll have to test that. I wasn't sure if you needed to process both upper and lower case so I did both. You could probably copy and use this encrypt function in your code. /* Assumes replacement_alphabet is at least as long as the alphabet(26). replacement_alphabet should be limited to lower case letters. Assumes the result has enough allocated memory to store the full length of input. */ void encrypt(const char * input, const char *replacement_alphabet, char * result) { int i; char c; // loop through all characters of input. for (i = 0; input[i] != '\0'; i++) { c = input[i]; if (c >= 'a' && c <= 'z') // if lower case result[i] = replacement_alphabet[c - 'a']; else if (c >= 'A' && c <= 'Z') // if upper case letter result[i] = replacement_alphabet[c - 'A'] + ('A' - 'a'); else result[i] = c; } result[i] = '\0'; // mark end of null-terminated string. } int main() { const char *replacement_alphabet = "vchprzgjntlskfbdqwaxeuymoi"; const char * input = "Hello, World"; char result[256]; /* plaintext: hello, world ciphertext: jrssb, ybwsp */ encrypt(input, replacement_alphabet, result); printf("%s", result); }
15th Apr 2021, 2:44 AM
Josh Greig
Josh Greig - avatar
0
Josh Greig just added to my code. It works great! Thank you so much!
15th Apr 2021, 3:57 AM
David
David - avatar
0
David wrote, "Josh Greig just added to my code. It works great! Thank you so much!" Response: good stuff.
15th Apr 2021, 4:03 AM
Josh Greig
Josh Greig - avatar