views:

152

answers:

4

i have an array of strings of phone numbers, and i have to insert hyphens into them. what string function should i use, and how? thanks. :D

A: 

Use STL string functions. Iterate over the array of strings, and for each string, do this:

str_num = str_num.substr(0,3) + "-" + str_num.substr(3,3) + "-" + str_num.substr(6,4);

EDIT: You can use insert() as well, I think that would be a better way.

Joy Dutta
No. You're concatenating.
wilhelmtell
That's really inefficient, it makes several unnecessary copies of the string.
Tim Sylvester
Thanks so much! it worked perfectly. :D
+1  A: 

Well, I won't give the answer away, but the simplest thing to do is to use the std::string::insert method, assuming you're doing C++.

For C strings, you'll have to manually copy the characters around. I would probably use sprintf.

Tim Sylvester
strncat would be the more useful C-style string function.
Roger Pate
You'd need at least three separate calls to `strcat` or similar, or you could do something like `sprintf(buf, "%.3s-%.3s-%.4s", s, s+3, s+6)`. Just a question of style, really.
Tim Sylvester
A: 

You could use strtok function to split it into tokens.

char * strtok ( char * str, const char * delimiters );
Secko
You can't split a without a delimiter. Where is the delimiter in a 10-digit number to split it to (3,3,4) digits ?
Joy Dutta
@Joy Dutta I agree, but when I posted the answer something else was on my mind. Now I would have used iterators.
Secko
A: 

What you want is to add two characters to each string, in two specific positions.

Create a function that takes a single phone number string and adds the hyphens where appropriate. This is a good example where it's easy to just use string concatenation, but it's a bad habit. Instead, you can use string::insert() to place the hyphens where appropriate.

Once you have this simple function written all you have to do is iterate over the array and apply the function on each element. Coincidentally the for_each() function can do just that. You will find it in <algorithm>.

#include<string>
#include<algorithm>

void with_hyphens(string& phone)
{
    // as explained above
}

// ...
{
    for_each(array, array + ARRAY_LENGTH, &with_hyphens);
}
wilhelmtell