开发者

insert a hyphen into a string C++

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?开发者_Python百科 thanks. :D


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.


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.


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);
}


You could use strtok function to split it into tokens.

char * strtok ( char * str, const char * delimiters );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜