Originally Posted by
nime
But (maybe I'm wrong) it seems that routines with char* is faster than those with strings what can be important when we have to replace some chars in million of strings.
I am working on that
By faster you mean:
1) execution speed, or
2) ease of implementation, ie, writing the coding
WRT #1, I dunno. Could be.
WRT #2, it's more the case that there are some C string functions and methods that are not perfectly duplicated with C++ string methods, but you can still use them on C++ strings, eg:
Code:
string str = "hello world";
char *p = strchr(str.c_str(),'w');
p[3] = 'X';
cout << p;
If you don't want to #include <cstring>, you could do this:
Code:
string str = "hello world";
string::size_type pos = str.find_first_of("w");
str[pos+3] = X;
cout << str.substr(pos,str.size()-pos);
which is certainly more awkward and long winded and probably does execute slower.
WRT coming from Visual Basic, two big things you will want to understand:
1) the difference between dynamic typing (VB) and static typing (C/C++)
2) the difference between dynamic memory allocation (VB and C++ strings) and static memory allocation (C strings).
The significance of the first one is, in C/C++, you must declare variables to be of a specific type and you cannot change them. Coming from VB, you probably have not had to think much about datatypes because VB uses dynamic typing.
The significance of the second one is that C arrays have a fixed sized.
mystring can only hold 20 characters, because it is an array. If you want to make it hold more, you need to declare it as a pointer, malloc() it memory, and then realloc() it later.
Also, in C/C++ you also must often take responsibility for "deallocating" or "freeing" memory when you are done using it. Coming from VB, you will not have needed to think about this as it is all automatic.
The major reason for these two differences is that VB is an interpreted language whereas C/C++ is compiled. No one really wants to put up with static typing or manual allocation, but up to now it has been impossible to create a compiled language with completely dynamic typing and allocation, so you have to deal with it.
I just said you cannot change a variable type in C/C++, but you can cast it. This is the case where you want to submit a C-string to a function that requires a C++ string:
Code:
void some_function(string str);
// to call with a C-string:
char mystring[] = "hello world";
some_function((string)mystring);
This is like how you can submit a C++ string as a C string using .c_str().
I imagine all this is maybe bewildering right now, but don't worry, it will all make sense eventually...