First uppercase letter in a string (Iterative and Recursive) in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how find the first uppercase letter in the given string. Let's see an example.

Input −Tutorialspoint

Output −T

Let's see the steps to solve the problem using iterative method.

  • Initialize the string.

  • Iterate over the string.

  • Check whether the current character is uppercase or not using isupper method.

  • If the character is uppercase than return the current character.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str) {
   for (int i = 0; i < str.length(); i++)
      if (isupper(str[i])) {
         return str[i];
      }
      return 0;
   }
   int main() {
      string str = "Tutorialspoint";
      char result = firstUpperCaseChar(str);
      if (result == 0) {
         cout << "No uppercase letter" << endl;
      }
      else {
         cout << result << endl;
      }
   return 0;
}

Output

If you run the above code, then you will get the following result.

T

Let's see the steps to solve the problem using recursive method.

  • Initialize the string.

  • Write a recursive function which accepts two parameter string and index.

  • If the current character is end of the string then return.

  • If the current character is uppercase then return the current character.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str, int i = 0) {
   if (str[i] == '\0') {
      return 0;
   }
   if (isupper(str[i])) {
      return str[i];
   }
   return firstUpperCaseChar(str, i + 1);
}
int main() {
   string str = "Tutorialspoint";
   char result = firstUpperCaseChar(str);
   if (result == 0) {
      cout << "No uppercase letter";
   }
   else {
      cout << result << endl;
   }
   return 0;
}

Output

If you run the above code, then you will get the following result.

T

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 29-Dec-2020 15:44:06
Advertisements