SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:14 | ISBN:9780136091813 | Edition: 2

Question

Write a method called swapPairs that accepts a String as a parameter and returns that String with each pair of adjacent letters reversed. If the String has an odd number of letters, the last letter is unchanged. For example, the call swapPairs("example") should return "xemalpe" and the call swapPairs("hello there") should return "ehll ohtree".

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer



public class PairsSwap {
	
	
	public static String swapPairs(String string) {
		
	
          
	        // convert that string to an array
		    char[] toChar = string.toCharArray();
		    
		    // run through loop two characters at a time
		    for(int i = 0; i <= toChar.length - 2; i += 2) {
		    	// swap function
		        char var = toChar[i];
		        toChar[i] = toChar[i+1];
		        toChar[i+1] = var;
		    }
		    
		    // convery string of characters into string again
		    String swappedString = new String(toChar);
		    
		    return swappedString;
		    
		   
		
	}
	

	public static void main(String[] args) {
		
		String swapped = PairsSwap.swapPairs("kishore");
		System.out.println("string after apply swapping: " +swapped);
		
		
	}

}
Output:

string after apply swapping: ikhsroe

}

 

0 0

Discussions

Post the discussion to improve the above solution.