tags:

views:

73

answers:

3

How can I take a string (in this case it'll be loaded from a file) then remove certain characters and store them in an array.

Ex:

f.e.d.r.t.g.f

remove "." to get f e d r t g f in an array where I can manipulate each individually

+1  A: 

You can loop over them, if the character is rejected go to next character (or return if no more chacters). If it is not rejected push it into the array. That would create a copy of the characters, but unless your string is gigantic it is not a problem. If it is, my answer wont suffice :)

Another variant would be a function that reads the string until it hits a valid character and returns it. To get the next character call the function again. The function needs to maintain an index variable passed to it though. If the end of the string is reached you would need to indicate it somehow.

Skurmedel
This same idea would work if you copy the characters in place, using two pointers, one for the write location and one for the read. Be sure to put a \0 at the end.
Joel
@Joel: Hmm yes,... good suggestion.
Skurmedel
+3  A: 

Just iterate through the string and only copy the characters you're interested in, maintaining an index of the current position in the new array.

Ignacio Vazquez-Abrams
+2  A: 

strtok() does this easily if

  1. the code is used in a single thread
  2. You don't mind if the source string is changed in the process.
Joel
+1 This might be the obvious solution. Also, reference: http://www.gnu.org/s/libc/manual/html_node/Finding-Tokens-in-a-String.html
Skurmedel
You can get around the first condition by using strtok_r().
Fred Larson
thanks! That's just what I was looking for
Matt S.
strtok_r is nonstandard. If you're using C it's because you want portable code usually.
Joel