Thread: array trimming...

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    45

    array trimming...

    Lets say I have an array like this:
    Code:
    char str[30] = "          Hello          ";
    How would I trim off all the leading and trailing whitespaces?
    I tried doing this with a cnt of all non ' ' then making a new array with the size of cnt. Then I noticed that I can't create an array with a variable. So how should I go about this?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Use a for loop to count the number of leading spaces
    Use another for loop to count the trailing spaces
    Use strncpy() to copy the bit in between

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    The problem you ran into is that unless you use dynamic memory allocation, the size of the array must be constant. Assuming you have not yet studied dynamic memory allocation, you can get around this using the std::string class in the <string> header. A quick reference on what you find in the class here: cpprefence.com's strings
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  3. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM