Home » C++ programs

C++ program to find and print first uppercase character of a string

In this C++ program, we are going to learn how to find and print first uppercase character of a given string? Here, string is given and we have to print (if exists) first uppercase character.
Submitted by IncludeHelp, on March 13, 2018

Given a string and we have to print its first uppercase character (if exists) using C++ program.

Example:

    Input string: "hello world, how are you?"
    Output:
    No uppercase character found in string.

    Input string: "Hello World"
    Output:
    First uppercase character is: "H"

    Input string: "hello worlD"
    Output:
    First uppercase character is: "D"

Logic:

To find uppercase character, we designed a user defined function named getFirstUppercaseCharacter() this function has a string argument and returns either first uppercase character (if exists) or 0 if there is no uppercase character in the string.

To check uppercase character - we are using a loop from 0 to str.length() and isupper() function which is a library function - it returns true if character is uppercase.

If first uppercase character is found, we are returning (return str[i];) program’s control from the loop, if there is no uppercase character, at the end of the loop, function returns 0.

Program to print first uppercase character of a string in C++



#include <bits/stdc++.h>
using namespace std;

//function to return first uppercase
//character from given string
char getFirstUppercaseCharacter(string str)
{
	//loop that will check uppercase character
	//from index 0 to str.length()
	for(int i=0; i<str.length(); i++)
	{
		//'isupper() function returns true
		//if given character is in uppercase
		if(isupper(str[i]))
			return str[i];
	}
	
	return 0;	
}

//Main function
int main()
{
	//defining two strings
	string str1 = "hello world, how are you?";
	string str2 = "Hello World";
	
	//first string check 
	cout<<"Given string: "<<str1<<endl;
	char chr = getFirstUppercaseCharacter(str1);
	if(chr)
		cout<<"First uppercase character is: "<<chr<<endl;
	else
		cout<<"No uppercase character found in string"<<endl;
	
	cout<<endl;

	//second string check 
	cout<<"Given string: "<<str1<<endl;
	chr = getFirstUppercaseCharacter(str2);
	if(chr)
		cout<<"First uppercase character is: "<<chr<<endl;
	else
		cout<<"No uppercase character found in string"<<endl;	
	
	return 0;
}

Output

Given string: hello world, how are you?
No uppercase character found in string

Given string: hello world, how are you?
First uppercase character is: H


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.