#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char firstname[] = "Alfred";
char middlename [] = "E";
char lastname[] = "Neuman";
char fullname [80];
int offset=0;
strcpy(fullname,firstname);
offset = strlen(firstname);
strcpy(fullname+offset," ");
offset +=1;
strcpy(fullname+offset,middlename);
offset += strlen(middlename);
strcpy(fullname+offset," . ");
offset +=2;
strcpy(fullname+offset,lastame);
cout << firstname << "." << middlename << "." << lastname << endl;
cout << "Fullname:" << fullname << 开发者_JAVA百科endl;
return 0;
}
Why is offset needed in this and why is the off set added by 1 and 2, when we are dealing with text. I cannot seem to grasp strings and Arrays, anyone mind helping?
That's because you're using the wrong tools.
std::string firstname = "Alfred";
std::string middlename = "E";
std::string lastname = "Numan";
std::string fullname = firstname + " " + middlename + " . " + lastname;
The offset is used to track the current position of the string in the array so that you can strcpy
the new argument into the right place.
You're adding the length of your separators (spaces) to the offset, so that you write the next part of the name in the correct location.
"offset" is being used to move the starting point for the copy operation to a point one character after the last character in the array. As more characters are copied into fullname, offset increases to point to the first character of the remaining unused space in the fullname array.
strcpy(fullname,firstname);
Copy the firstname into the fullname buffer.
offset = strlen(firstname);
Set the offset equal to the length of firstname so you know where to start copying the next thing into the fullname buffer, in this case an empty space character.
offset +=1;
Move your offset passed that character so you start copying into the fullname buffer from that point on.
strcpy(fullname+offset,middlename);
Copy the middle name into fullname buffer.
offset += strlen(middlename);
Add the length of middlename to the offset, again so the next copy operation starts right after that.
strcpy(fullname+offset," . ");
Copy in a '.' for the middle initial.
offset +=2;
Increase your offset to point right passed that.
strcpy(fullname+offset,lastame);
Copy in the last name.
Understand these two statements and then it is a pencil paper exercise.
- Array index starts from 0.
arrayVariable + integer
is the index at theinteger + 1
location in thearrayVariable
sequence. So,arr+3
is the location 4 in the sequence. ( Since array index starts from 0. )
精彩评论