raging fire
raging fire

Reputation: 29

Add character in middle of string

Been stuck on this for bloody ages. Seems like no easy way to do it!

Would appricate some help, thanks!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char (char *s, const int len) {
{
   static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                  "123456789";
   for (int i = 0; i < len; ++i) {
        s[i] = alphanum[(sizeof(alphanum) - 6)];
    }

    s[len] = 0;
    memmove(s+pos+1, s+pos, len-pos+1);
    s[pos]='-';
    puts(s);
}

int main (void)
{
//print the random digits but in the middle need to insert - e.g
//FJ3-FKE
}

Upvotes: 1

Views: 5004

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void func(char *s, int len, int pos) {
    static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                   "123456789";
    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand()%(sizeof(alphanum)-1)];
    }
    s[len] = 0;

    if(0 < pos && pos < len){
        memmove(s+pos+1, s+pos, len-pos+1);
        s[pos]='-';
    }
}

int main (void){
    char s[10];
    srand(time(NULL));
//print the random digits but in the middle need to insert - e.g
//FJ3-FKE
    func(s, 6, 3);
    puts(s);
    return 0;
}

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126937

There are two easy ways.

If you just need to print that stuff, you can add the dash just in the output, like this:

fwrite(s, pos, stdout);
putchar('-');
puts(s+pos);

In alternative, if the buffer used for s is big enough to accommodate one more char, you can use memmove to make space for the dash, add the dash and then print the string:

memmove(s+pos+1, s+pos, len-pos+1);
s[pos]='-';
puts(s);

(all this supposing that pos is the position where to insert the dash)

Upvotes: 3

Related Questions