- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- 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
- Searching characters in a String in Java.
- Convert a String to a List of Characters in Java
- Remove all non-alphabetical characters of a String in Java?
- Convert List of Characters to String in Java
- Searching characters and substring in a 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 find duplicate characters in a String?
- Program to equal two strings of same length by swapping characters in Python
- Java program to check order of characters in string
- Java program to convert a list of characters into a string
- Displaying at most 10 characters in a string in Java

Advertisements