insert a char anywhere in a string

This is a discussion on insert a char anywhere in a string within the C Programming forums, part of the General Programming Boards category; Hello, is there a function with which i can add characters anywhere in a string? i have been searching for ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    13

    insert a char anywhere in a string

    Hello, is there a function with which i can add characters anywhere in a string? i have been searching for something like that but i cant find anything. Should i do my own functions for something like that? Does anything like stringbuffer apply in C?

    Thanks.

  2. #2
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    978
    There is no standard function; you'll have to do it on your own.

    You'll probably want to use memmove() to copy part of the string to the right so there's space to insert your new character(s). Don't forget to make sure that there's enough space past the end of the string to copy into. If not, you'll have to expand the buffer with realloc() if you allocated it with malloc(), or copy it into a whole new buffer.

    C is not the world's best language for text processing.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    13
    thanks!

    but can i choose the position where memmove will start copying the string? or it always starts from the beginning of the string? can i do that with a pointer?

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Quote Originally Posted by panosstylianou View Post
    thanks!

    but can i choose the position where memmove will start copying the string? or it always starts from the beginning of the string? can i do that with a pointer?
    Yes.

    Code:
    char *a = "abcd";
    char *b = "wxyz";
    
    memmove(&a[1], &b[0], 4); /*will move b (starting at pos. 0) to a (starting at pos. 1) */
    
    memmove(a + 1, b + 0, 4); /*will do the exact same thing */

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 06-16-2011, 11:59 AM
  2. Replies: 2
    Last Post: 09-12-2010, 09:15 AM
  3. Insert int into string
    By lpmrhahn in forum C Programming
    Replies: 1
    Last Post: 04-09-2004, 02:10 PM
  4. Insert char into string?
    By Zwen in forum C++ Programming
    Replies: 5
    Last Post: 09-29-2002, 05:27 PM
  5. How do I insert a char in an unsigned long* v?
    By Robert in forum C++ Programming
    Replies: 17
    Last Post: 07-02-2002, 04:03 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21