
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find First Maximum Length Even Word from a String in C++
In this problem, we are a string str consisting of comma separated words. Our task is to find the first maximum length, even word, from a string.
We need to find the largest word 'string between two spaces' whose length is maximum and even.
Let's take an example to understand the problem,
Input : str = "learn programming at TutorialsPoint" Output : TutorialsPoint
Explanation −
The string with even length is TutorialsPoint.
Solution Approach
A simple solution to the problem is by simply finding the string which has even length greater than the current string. Initialise the maxString length to 0.
Algoritham
Step 1 − Iterate over the string.
Step 2 − check if the current word has even length and the length of word is greater than last greater word.
Step 3 − Return the word.
Example
Program to illustrate the working of our solution
#include <bits/stdc++.h> using namespace std; string findMaxEvenLenWord(string str) { int len = str.length(); int i = 0; int currWordlen = 0; int maxWordLen = 0; int stringPointer = -1; while (i < len) { if (str[i] == ' ') { if (currWordlen % 2 == 0) { if (maxWordLen < currWordlen) { maxWordLen = currWordlen; stringPointer = i - currWordlen; } } currWordlen = 0; } else { currWordlen++; } i++; } if (currWordlen % 2 == 0) { if (maxWordLen < currWordlen) { maxWordLen = currWordlen; stringPointer = i - currWordlen; } } if (stringPointer == -1) return "Not Found!"; return str.substr(stringPointer, maxWordLen); } int main() { string str = "Learn programming at Tutorialspoint"; cout<<"The maximum length even word is '"<<findMaxEvenLenWord(str)<<"'"; return 0; }
Output
The maximum length even word is 'Tutorialspoint'
Advertisements