简体   繁体   English

有没有办法在 C 中重复字符串中的字符?

[英]Is there a way to repeat characters in a string in C?

I'm making a Vigenère cipher implementation in Arduino;我正在 Arduino 中实现 Vigenère 密码; and I wanted to build the functions in C first, just to get the hang of things.我想先构建 C 中的功能,只是为了掌握一些东西。

My key strings will be stored in the arduino, and they will be randomly selected to encrypt the message the user enters.我的密钥字符串将存储在 arduino 中,它们将被随机选择以加密用户输入的消息。 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"?例如,如果存储的密钥是“axudni”,消息是“rideatdawn”,有没有办法更改密钥字符串,使其变为“axudniaxud”?

Something akin to this: https://stackoverflow.com/a/14992905/14103580类似的东西: 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 ).我认为这是一个 X/Y 问题( 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. ) 我在此承认这个概念已经在 Weather Vane 的明显较旧的评论中。在添加我的答案之前我根本没有注意到。

Ie instead of reading like this repeatedkeystring[i] access like keystring[i%keylength] .即,而不是像keystring[i%keylength]这样repeatedkeystring[i]访问。

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.我相信/假设“我正在制作一个 vignere 密码实现”意味着您自己可以决定访问密钥的这种细节。 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).如果您使用的库需要例如指向 memory 中足够长的字符序列的指针(可能是指向 char、 const char* const的指针),那么您肯定需要遵循乘法方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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