copying strings efficiently?

M

Mark van Heeswijk

Probably a very basic question but i'm new to c++

What's the most efficient (mem) way to copy string 'a' to string 'b'? Now i
do:

char a[1000];
char* b; // length not known...could be 1000
strcpy(a, b);

Is it really necessary that 'a' always gets allocated the max size of 'b',
or can this be done more efficiently?

Thanks in advance,
Mark
 
J

John Harrison

Mark van Heeswijk said:
Probably a very basic question but i'm new to c++

What's the most efficient (mem) way to copy string 'a' to string 'b'? Now i
do:

char a[1000];
char* b; // length not known...could be 1000
strcpy(a, b);

Is it really necessary that 'a' always gets allocated the max size of 'b',
or can this be done more efficiently?

Thanks in advance,
Mark

The most efficient way to copy a string is to use the std::string class.

#include <string>

std::string a = whatever;
std::string b = a; // copies string a to string b

Don't mess around with char arrays, learn some proper C++ and use the C++
string class.

john
 
N

Newsnet Customer

What's the most efficient (mem) way to copy string 'a' to string 'b'?
Now
i
do:

char a[1000];
char* b; // length not known...could be 1000
strcpy(a, b);

Is it really necessary that 'a' always gets allocated the max size of 'b',
or can this be done more efficiently?

Thanks in advance,
Mark

The most efficient way to copy a string is to use the std::string class.

#include <string>

std::string a = whatever;
std::string b = a; // copies string a to string b

Don't mess around with char arrays, learn some proper C++ and use the C++
string class.


what is the std namespace used for? used for all C++ header files?

asasas
 
J

John Harrison

Newsnet Customer said:
What's the most efficient (mem) way to copy string 'a' to string 'b'?
Now
i
do:

char a[1000];
char* b; // length not known...could be 1000
strcpy(a, b);

Is it really necessary that 'a' always gets allocated the max size of 'b',
or can this be done more efficiently?

Thanks in advance,
Mark

The most efficient way to copy a string is to use the std::string class.

#include <string>

std::string a = whatever;
std::string b = a; // copies string a to string b

Don't mess around with char arrays, learn some proper C++ and use the C++
string class.


what is the std namespace used for? used for all C++ header files?

asasas

The std namespace is for the C++ standard library, which means things like
std::string, std::cout, std::vector, std::map etc. Any standard header file
without a .h is the C++ standard library.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top