Repeating contents of a char array if size < than X

I am wondering about how one could repeat the content of a char array if the size of the array is less than a spesific size?

Here is what I tried:

1
2
3
4
5
if(strlen(charArray) < wantedSize) {
   for (int i = 1; i <= wantedSize; i++) {
        charArray[strlen(charArray) + i] = charArray[i];
   }
}


But this does not give me anything. So I am kinda stuck.

Any help?
You have to write it yourself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string.h>

char* replicate_cstring( char* s, size_t newsize ) 
// s must have at least newsize + 1 characters
{
  size_t oldsize = strlen( s );
  while (oldsize + oldsize < newsize)
  {
    strncpy( s + oldsize, s, oldsize );
    oldsize += oldsize;
  }
  if (oldsize < newsize)
    strncpy( s + oldsize, s, newsize - oldsize );
  s[newsize] = '\0';
  return s;
}

Enjoy!
Thank you @Duthomhas. But I played around a little and found another solution to it!

RE: Don't use this snippet. It's garbage. See @lastchance's answer below.

1
2
3
4
5
6
7
8
9
char charArray[256];

if (charArray < anotherArray) {
	int charArraySize = strlen(charArray);
	for (int i = 0; i < strlen(anotherArray); i++) {
		charArray[(sizeof(charArray) - 255) + i] = charArray[(i + 1) % charArraySize];
	}
	charArray[strlen(anotherArray)] = '\0';
}
Last edited on
@An_Integer, I'm trying to work out how many lines of your "solution" make any sense at all.

If a "friend" gave it to you then you've been had!

If you re-order the declarations of charArray and anotherArray ... you will (probably) get a different answer. What do you think the line
if (charArray < anotherArray)
does? That would compare memory locations, not c-string lengths.

Also,
charArray[(sizeof(charArray) - 255) + i]
is a pretty daft (and non-robust) way of writing
charArray[i+1]


Try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
   char charArray[256]="12345";
   char anotherArray[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   cout << charArray << '\n';

   if ( strlen(charArray) < strlen(anotherArray) )
   {
      int charArraySize = strlen(charArray);
      for (int i = charArraySize; i < strlen(anotherArray); i++) charArray[i] = charArray[i-charArraySize];
      charArray[strlen(anotherArray)] = '\0';
   }
   cout << charArray << '\n';
}
Last edited on
Thank you so much @lastchance! That really did the trick. The "thing" I wrote was apparently complete bogus. I should edit the reply and give a warning about it. Because this:

"If you re-order the declarations of charArray and anotherArray ... you will (probably) get a different answer. What do you think the line..."

Saved the whole program. I was having problems doing other things with the program, even though it worked fine with what I first wrote.
Last edited on
Topic archived. No new replies allowed.