Obtain the first or last word inside a string in C++

If you do a lot of work with strings in C++, one thing you’ll probably find yourself doing is writing utility functions. The String class provides many useful built-in methods, but when it comes to searching, replacing and text manipulation, you may find that you’ll need to create your own functions to carry out these tasks, sometimes using and combining the built-in class methods to carry out more complex tasks within your projects.

The two following functions can be used to obtain the first and last words contained within a string. An empty string is returned if the function fails. The functions make use of the built in String methods find_first_of and find_last_of;

Having a decent set of your own utility functions can save a lot of time, and will make your code a lot more manageable. A good strategy for code re-usability is to break up a bigger task into smaller functions that you can see yourself re-using in the future, saving yourself both time and making your code easier to understand.

This is akin to your toolbox, and if you find yourself needing the same tool over and over again, then that’s when it’s a good idea to write your own utility function or use someone else’s. There’s always that temptation to write everything for yourself, but one of the key aspects of code re-usability is to not re-invent the wheel.

Writing your own utility functions does have some benefits, however. Firstly, you’ll understand the code very well and learn new techniques, and secondly, it can improve your overall skills as a programmer, especially in problem solving. So yes, there are times when it is better to write your own, and other times when using someone else’s solution is the best approach. You may even decide to compromise by checking other people’s solutions to help you write you own. There’s no right or wrong way to approach it. Take the approach that suits you or the situation best.

Leave a Reply

Your email address will not be published. Required fields are marked *