简体   繁体   中英

Is there a way to repeat characters in a string in C?

I'm making a Vigenère cipher implementation in Arduino; and I wanted to build the functions in C first, just to get the hang of things.

My key strings will be stored in the arduino, and they will be randomly selected to encrypt the message the user enters. However, the keys will be of a fixed length, and the length of the message could be longer than the key.

Is it possible to repeat characters in a string until the string is of a certain length?

For example, if the key stored is "axudni" and the message is "rideatdawn", is there a way to change the key string so that is becomes "axudniaxud"?

Something akin to this: https://stackoverflow.com/a/14992905/14103580

I just need to be pointed in the right way, and guidance would be greatly appreciated.

I consider this to be an X/Y problem ( https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem ).

I suspect that creating a suitable repeated key string is a possible but inelegant solution.

Instead I propose to use the keys by accessing them via the modulo of the index you would use into the repeated string.

( I hereby admit to the concept being already in the noticably older comment by Weather Vane. I simply did not notice before adding my answer. )

Ie instead of reading like this repeatedkeystring[i] access like keystring[i%keylength] .

Note:
I trust/assume that "I'm making a vignere cipher implementation" means that you yourself can decide this kind of detail of accessing the keys. If you are using a library which requires eg a pointer to a sufficiently long character sequence in memory (pointer to char, const char* const , maybe), then you will admittedly need to follow the multiplying approach).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM