

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swapping Characters of a String in Java
For swapping characters of a string in Java we can use string builder which is mutable so we need not to take care of new object creation during swapping.
In this we would create a method which swap characters of string based on location of swapping characters.This method will take location of swapping characters as its parameters.First store both characters need to be swapped and using set character method of string builder swap the targeted characters.
Example
public class SwapCharacters { public static void main(String[] args) { String str = "abcde"; System.out.println(swap(str,0,1)); System.out.println(swap(str,0,str.length()-1)); } static String swap(String str , int i , int j ) { StringBuilder strB = new StringBuilder(str); char l = strB.charAt(i) , r = strB.charAt(j); strB.setCharAt(i,r); strB.setCharAt(j,l); return strB.toString(); } }
Output
bacde ebcda
- Related Questions & Answers
- Swapping Characters of a String in C#
- Maximum length of balanced string after swapping and removal of characters in C++
- Swapping adjacent words of a String in JavaScript
- Convert a String to a List of Characters in Java
- Searching characters in a String in Java.
- Remove all non-alphabetical characters of a String in Java?
- Convert List of Characters to String in Java
- Swapping string case using a binary number in JavaScript
- Count the Number of matching characters in a pair of Java string
- Java program to convert a list of characters into a string
- Regrouping characters of a string in JavaScript
- Program to equal two strings of same length by swapping characters in Python
- Searching characters and substring in a String in Java
- Java program to check order of characters in string
- Java Program to find duplicate characters in a String?
Advertisements