Remove odd indexed characters from a given string
Last Updated :
09 Dec, 2022
Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string.
Examples :
Input: str = “abcdef”
Output: ace
Explanation:
The characters ‘b’, ‘d’ and ‘f’ are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed from the string.
Input: str = “geeks”
Output: ges
Approach: Follow the steps below to solve the problem:
- Initialize an empty string, say new_string, to store the result.
- Traverse the given string and for every index, check if it is even or not.
- If found to be true, append the characters at those indices to the string new_string.
- Finally, after complete traversal of the entire string, return the new_string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string removeOddIndexCharacters(string s)
{
string new_string = "" ;
for ( int i = 0; i < s.length(); i++) {
if (i % 2 == 1) {
continue ;
}
new_string += s[i];
}
return new_string;
}
int main()
{
string str = "abcdef" ;
cout << removeOddIndexCharacters(str);
return 0;
}
|
Java
import java.util.*;
class GFG {
static String removeOddIndexCharacters(
String s)
{
String new_string = "" ;
for ( int i = 0 ; i < s.length(); i++) {
if (i % 2 == 1 )
continue ;
new_string += s.charAt(i);
}
return new_string;
}
public static void main(String[] args)
{
String str = "abcdef" ;
str = removeOddIndexCharacters(str);
System.out.print(str);
}
}
|
Python3
def removeOddIndexCharacters(s):
new_s = ""
i = 0
while i < len (s):
if (i % 2 = = 1 ):
i + = 1
continue
new_s + = s[i]
i + = 1
return new_s
if __name__ = = '__main__' :
str = "abcdef"
str = removeOddIndexCharacters( str )
print ( str )
|
C#
using System;
class GFG{
static string removeOddIndexCharacters( string s)
{
string new_string = "" ;
for ( int i = 0; i < s.Length; i++)
{
if (i % 2 == 1)
continue ;
new_string += s[i];
}
return new_string;
}
public static void Main()
{
string str = "abcdef" ;
str = removeOddIndexCharacters(str);
Console.Write(str);
}
}
|
Javascript
function removeOddIndexCharacters(s)
{
var new_string = "" ;
for ( var i = 0; i < s.length; i++) {
if (i % 2 === 1) {
continue ;
}
new_string += s[i];
}
return new_string;
}
string str = "abcdef" ;
console.log(removeOddIndexCharacters(str));
|
Time Complexity: O(N)
Auxiliary Space: O(N)