Swapping Pairs of Characters in a String in Java
Last Updated :
20 Feb, 2024
Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is.
Examples:
Input: str = “Java”
Output: aJav
Explanation: The given string contains even number of characters. Therefore, we swap every pair of characters.
Input: str = “GeeksForGeeks”
Output: eGkeFsroeGkes
Explanation: The given string contains odd number of characters. Therefore, we swap every pair of characters and last character remains as it is.
- Get the string to swap a pair of characters.
- Check if the string is null or empty then return the string.
- Converting the given string into a character array.
- Traverse the character array and swap the characters.
- Now, print the result.
Java
class GFG {
public static String swapPair(String str)
{
if (str == null || str.isEmpty())
return str;
char [] ch = str.toCharArray();
for ( int i = 0 ; i < ch.length - 1 ; i += 2 ) {
char temp = ch[i];
ch[i] = ch[i + 1 ];
ch[i + 1 ] = temp;
}
return new String(ch);
}
public static void main(String args[])
{
String str = "GeeksForGeeks" ;
System.out.println(swapPair(str));
}
}
|
- Get the string to swap a pair of characters.
- Check if the string is null or empty then return the string.
- Creating a StringBuffer object with a length of the string passed as a parameter.
- Traverse the string and append the characters in the StringBuffer object in reverse order.
- Check if the string contains an odd number of characters then append the last character into the StringBuffer object.
- Now, print the result.
Java
class GFG {
public static String swapPairs(String str)
{
if (str == null || str.isEmpty())
return str;
int len = str.length();
StringBuffer sb = new StringBuffer(len);
for ( int i = 0 ; i < len - 1 ; i += 2 ) {
sb.append(str.charAt(i + 1 ));
sb.append(str.charAt(i));
}
if (len % 2 != 0 ) {
sb.append(str.charAt(len - 1 ));
}
return sb.toString();
}
public static void main(String args[])
{
String str = "GeeksForGeeks" ;
System.out.println(swapPairs(str));
}
}
|
Share your thoughts in the comments
Please Login to comment...