Capitalize 1st character of all words having at least K characters
Last Updated :
16 Feb, 2022
Given string str representing a sentence, and an integer K, the task is to capitalize all the words in the given sentence having at least K characters.
Example:
Input: str = “geeks for geeks”, K = 4
Output: Geeks for Geeks
Explanation: The word “for” does not contain 4 characters, hence its 1st character is not capitalize.
Input: str = “geeksforgeeks is the best”, K = 0
Output: Geeksforgeeks Is The Best
Approach: This is an implementation-based problem.
- The idea is to calculate the character count of each word and,
- if the count of characters is greater than K,
- change the case of the 1st character of the word to the upper case
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string capitalizeStr(string str, int K)
{
int ptr = 0;
for ( int i = 0; i < str.size(); i++) {
if (str[i] == ' ' ) {
ptr = i + 1;
}
else if (i - ptr + 1 >= K) {
str[ptr] = toupper (str[ptr]);
}
}
return str;
}
int main()
{
string str = "geeksforgeeks is the best" ;
int K = 0;
cout << capitalizeStr(str, K);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static String capitalizeStr(String str, int K)
{
int ptr = 0 ;
char [] ch = str.toCharArray();
for ( int i = 0 ; i < ch.length; i++) {
if (ch[i] == ' ' ) {
ptr = i + 1 ;
}
else if (i - ptr + 1 >= K) {
ch[ptr] = Character.toUpperCase(ch[ptr]);
}
}
String s = new String(ch);
return s;
}
public static void main(String args[])
{
String str = "geeksforgeeks is the best" ;
int K = 0 ;
System.out.println(capitalizeStr(str, K));
}
}
|
Python3
def capitalizeStr( str , K):
str = list ( str )
ptr = 0
for i in range ( 0 , len ( str )):
if ( str [i] = = ' ' ):
ptr = i + 1
elif (i - ptr + 1 > = K):
str [ptr] = str [ptr].upper()
return "".join( str )
if __name__ = = "__main__" :
str = "geeksforgeeks is the best"
K = 0
print (capitalizeStr( str , K))
|
C#
using System;
class GFG {
static string capitalizeStr( string str, int K)
{
int ptr = 0;
char [] ch = str.ToCharArray();
for ( int i = 0; i < ch.Length; i++) {
if (ch[i] == ' ' ) {
ptr = i + 1;
}
else if (i - ptr + 1 >= K) {
ch[ptr] = Char.ToUpper(ch[ptr]);
}
}
string s = string .Concat(ch);
return s;
}
public static void Main()
{
string str = "geeksforgeeks is the best" ;
int K = 0;
Console.WriteLine(capitalizeStr(str, K));
}
}
|
Javascript
<script>
function capitalizeStr(str, K)
{
str = str.split( "" )
let ptr = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] == ' ' ) {
ptr = i + 1;
}
else if (i - ptr + 1 >= K) {
str[ptr] = str[ptr].toUpperCase()
}
}
return str.join( "" );
}
let str = "geeksforgeeks is the best" ;
let K = 0;
document.write(capitalizeStr(str, K))
</script>
|
Output
Geeksforgeeks Is The Best
Time Complexity: O(N), where N is the count of characters in string str.
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...