How to create half of the string in uppercase and the other half in lowercase?
Last Updated :
23 Jul, 2025
The first thing that we have to keep in my mind while solving this kind of problem is that the strings are immutable i.e,
If I am taking the following string
var string1 = "geeksforgeeks";
string1[0] = "G";
console.log(string1);
As strings are immutable, so we cannot change the character of the string, so the output of the above code will be the following.
Output:
geeksforgeeks
Approach:
There are several ways to solve this problem. Some of them are as follows.
- Splitting the string into 2 different parts and changing the first part to the UPPERCASE and concatenating the new strings to get the output.
- Create an empty string and add each character of the string to it using FOR loop.
- Using the slicing property of strings to get the output.
Method 1: This method is implemented using 2 new variables.
- Add the string into the variable.
- Store the length of the string into a variable using string.length function.
- Create two empty strings which are used in the future to store the newly created strings.
- Use of for loops to traverse in the string.
- Convert the first string to the upper case using toUpperCase().
- Concatenate both of the strings to get the output.
C++
#include <iostream>
using namespace std;
int main() {
string str = "geeksforgeeks",ans;
int len = str.length();
for(int i = 0;i<len;i++){
if(i<=len/2){
char a = toupper(str[i]);
ans.push_back(a);
}else
ans.push_back(str[i]);
}
cout<<ans;
return 0;
}
// This code is co ntributed by rohitsingh07052
Java
public class GFG {
public static void main(String[] args) {
// Input string
String str = "geeksforgeeks";
// StringBuilder to store the result
StringBuilder ans = new StringBuilder();
// Get the length of the input string
int len = str.length();
// Loop through each character in the input string
for (int i = 0; i < len; i++) {
// Check if the current character is in the first half of the string
if (i <= len / 2) {
// Convert the character to uppercase and append it to the result
char a = Character.toUpperCase(str.charAt(i));
ans.append(a);
} else {
// If the character is in the second half, just append it as is
ans.append(str.charAt(i));
}
}
// Print the final result
System.out.println(ans);
}
}
Python3
import math
string1 = 'geeksforgeeks'
string1_len = len(string1)
part_a = ''
part_b = ''
for i in range(int(math.ceil(string1_len // 2 + 1))):
part_a += string1[i]
for i in range(int(math.ceil(string1_len // 2)) + 1,
string1_len):
part_b += string1[i]
new_part_a = part_a.upper()
changed_string = new_part_a + part_b
print(changed_string)
# This code is contributed by ukasp
C#
using System;
public class GFG
{
public static void Main(string[] args)
{
// Input string
string str = "geeksforgeeks";
// String builder to store the result
System.Text.StringBuilder ans = new System.Text.StringBuilder();
// Get the length of the input string
int len = str.Length;
// Loop through each character in the input string
for (int i = 0; i < len; i++)
{
// Check if the current character is in the first half of the string
if (i <= len / 2)
{
// Convert the character to uppercase and append it to the result
char a = char.ToUpper(str[i]);
ans.Append(a);
}
else
{
// If the character is in the second half, just append it as is
ans.Append(str[i]);
}
}
// Print the final result
Console.WriteLine(ans);
}
}
JavaScript
<script>
var string1 = 'geeksforgeeks';
var string1_len = string1.length;
var part_a = '';
var part_b = '';
for(var i=0 ; i<Math.ceil(string1_len/2) ; i++)
{
part_a+=string1[i];
}
for(var i=Math.ceil(string1_len/2) ; i<string1_len ; i++)
{
part_b+=string1[i];
}
var new_part_a = part_a.toUpperCase();
var changed_string = new_part_a + part_b;
console.log(changed_string);
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 2: This method is implemented using a single new variable.
- Add the string into the variable.
- Store the length of the string into a variable using string.length function.
- Create an empty string that is used in the future to store the newly created string.
- Use of for loops to traverse the string.
- Log the final string to get the output.
C++
#include <iostream>
using namespace std;
string convertFun(string& s1, int n)
{
string ans = "";
// Running loop on first half and making it
// upper case
for (int i = 0; i < n / 2; i++) {
ans += toupper(s1[i]);
}
// Running loop on secone half
for (int i = n / 2; i < n; i++) {
ans += s1[i];
}
return ans;
}
// Driver code
int main()
{
string s1 = "geeksforgeeks";
// Finding length of string
int n = s1.size();
cout << convertFun(s1, n);
return 0;
}
// This code is added by Arpit Jain
Java
public class StringConversion {
// Function to convert the first half of the string to
// uppercase
static String convertFun(String s1, int n)
{
StringBuilder ans = new StringBuilder();
// Running loop on the first half and making it
// uppercase
for (int i = 0; i < n / 2; i++) {
ans.append(Character.toUpperCase(s1.charAt(i)));
}
// Running loop on the second half
for (int i = n / 2; i < n; i++) {
ans.append(s1.charAt(i));
}
return ans.toString();
}
// Driver code
public static void main(String[] args)
{
String s1 = "geeksforgeeks";
// Finding the length of the string
int n = s1.length();
System.out.println(convertFun(s1, n));
}
}
Python3
import math
string1 = 'gfg';
string1_len = len(string1)
changed_string = ''
for i in range(math.ceil(string1_len/2)):
changed_string += string1[i].upper();
for i in range(math.ceil(string1_len/2), string1_len):
changed_string += string1[i]
print(changed_string)
# This code is contributed by avanitrachhadiya2155
C#
using System;
class Program
{
// Function to convert the first half of the string to uppercase
static string ConvertFun(string s1, int n)
{
string ans = "";
// Running loop on the first half and making it upper case
for (int i = 0; i < n / 2; i++)
{
ans += char.ToUpper(s1[i]);
}
// Running loop on the second half
for (int i = n / 2; i < n; i++)
{
ans += s1[i];
}
return ans;
}
// Driver code
static void Main()
{
string s1 = "geeksforgeeks";
// Finding the length of the string
int n = s1.Length;
Console.WriteLine(ConvertFun(s1, n));
// This code is added by Arpit Jain
}
}
// This code is contributed by shivamgupta310570
JavaScript
<script>
var string1 = 'gfg';
var string1_len = string1.length;
var changed_string = '';
for(var i=0 ; i<Math.ceil(string1_len/2) ; i++)
{
changed_string+=string1[i].toUpperCase();
}
for(var i=Math.ceil(string1_len/2) ; i<string1_len ; i++)
{
changed_string+=string1[i];
}
console.log(changed_string);
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 3: This method is implemented using the JavaScript Slice property.
- Add the string into the variable.
- Store the length of the string into a variable using string.length function.
- Store the ceil value of half of the length of the string to the new variable.
- Create 2 empty strings which are used in the future to store the newly created strings.
- Add string to the variables using string slicing property.
- Convert the first string to the upper case using toUpperCase().
- Concatenate both of the strings to get the output.
C++
#include <cmath>
#include <iostream>
int main()
{
// Given string
std::string string1 = "geeks for geeks";
// Calculate the length of the string
int string1Len = string1.length();
// Calculate the index to split the string into two
// halves
int halfString
= static_cast<int>(std::ceil(string1Len / 2.0));
// Declare variables to store the two parts of the
// string
std::string partA;
std::string partB;
// Extract the first half of the string
partA = string1.substr(0, halfString);
// Convert the first half to uppercase
for (char& ch : partA) {
ch = std::toupper(ch);
}
// Extract the second half of the string
partB = string1.substr(halfString, string1Len);
// Concatenate the modified first half and the second
// half
std::string changedString = partA + partB;
// Print the modified string
std::cout << changedString << std::endl;
return 0;
}
Java
public class Main {
public static void main(String[] args) {
// Given string
String string1 = "geeks for geeks";
// Calculate the length of the string
int string1Len = string1.length();
// Calculate the index to split the string into two halves
int halfString = (int) Math.ceil(string1Len / 2.0);
// Declare variables to store the two parts of the string
String partA;
String partB;
// Extract the first half of the string
partA = string1.substring(0, halfString);
// Convert the first half to uppercase
String newPartA = partA.toUpperCase();
// Extract the second half of the string
partB = string1.substring(halfString, string1Len);
// Concatenate the modified first half and the second half
String changedString = newPartA + partB;
// Print the modified string
System.out.println(changedString);
}
}
Python3
import math
string1 = 'geeksforgeeks'
string1_len = len(string1)
half_string = math.ceil(string1_len/2)
part_a = ''
part_b = ''
part_a = string1[:half_string]
new_part_a = part_a.upper()
part_b = string1[half_string:string1_len]
changed_string = new_part_a+part_b
print(changed_string)
# This code is contributed by rag2127
C#
using System;
class Program
{
static void Main()
{
// Given string
string string1 = "geeks for geeks";
// Calculate the length of the string
int string1Len = string1.Length;
// Calculate the index to split the string into two halves
int halfString = (int)Math.Ceiling(string1Len / 2.0);
// Extract the first half of the string
string partA = string1.Substring(0, halfString);
// Convert the first half to uppercase
partA = partA.ToUpper();
// Extract the second half of the string
string partB = string1.Substring(halfString, string1Len - halfString);
// Concatenate the modified first half and the second half
string changedString = partA + partB;
// Print the modified string
Console.WriteLine(changedString);
}
}
JavaScript
<script>
var string1 = 'geeks for geeks';
var string1_len = string1.length;
var half_string = Math.ceil(string1_len/2);
var part_a;
var part_b;
part_a = string1.slice(0,half_string);
var new_part_a = part_a.toUpperCase();
part_b = string1.slice(half_string,string1_len);
var changed_string = new_part_a+part_b;
console.log(changed_string);
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
In these ways, you can solve these kinds of problems.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem