C Pointer Program to get the last name from a full name

C Language Flag / Logo

Another C programming here, this article will simply explain how to do char array operation in C language to get the last word from a whole sentence, or in this case we just rename our function to be more specific to get a person last name from its full name.

This is a very simple C function to get a user last name from a user full name. This function will do some pointer operation, so if you are trying to learn about pointer in C, this may help you little bit on understanding about a pointer in C:
char * get_last_name(char * full_name) {
   char *last_name = full_name;
   int last_space=0;
   for(int i=0; i 0) last_space+=1;
   last_name += last_space;
   return last_name;
}
This function will loop through all the characters bit by bit and will try to find any spaces located on that character. If a space is found, then store the last space pointer location and return that pointer as its function return.

- We define our function called get_last_name to receive a char pointer from a person's full name pointer.
- This function will return the pointer of the person's last name from the specified full_name parameter.
- char *last_name = full_name ⇒ make a copy of full_name pointer, stored in last_name pointer.
- int last_space=0 ⇒this variable will store the last space of a word, initially define the location to 0.
- Loop from 0, until it reaches the number of length full_name.
- check each character if it's a space or not, if space, then update last_space with current loop number i.
- If last_space is not 0, meaning it found a space in a word, we add 1 to the variable last_space because the current last_space is starting from space character not a letter, but what we need is a pointer starting after that space.
- Now add a last_name pointer with the number of last_space positions, so now the last_name pointer is located exactly on full_name last space plus 1.

Here’s my full code of the program that users ask to input their full name and in return the program will tell the person their last name.



C is very old, very simple, has no syntactic sugar like in any higher level language. Yet it was very exciting to learn. One of the most powerful languages that have been and still continue to be used in large projects that need to talk directly to the machine. C is very concise and capable of doing lower level stuff, that is what makes any program built in C will run faster, because it compiles to machine code, no need for interpreter or VM like execution.

Comments

Popular posts from this blog

ASUS Battery Health Charging Software To Make Your Battery Life Longer

Flutter AppBar, With Icon, Title and Actions Link

Flutter Button With Left Align Text and Icon

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

How To Create Spring Boot Project Using Netbeans