Swapping string in java

Swap Characters in String Java

Swap Characters in String Java | Java provides several built-in methods to swap characters in the string, it has made programmers easy by providing such methods. Let us see different ways available to swap characters in a string Java.

Example of swapping characters in a string Java:-

String str = "Know Program"; System.out.println(str); System.out.println(swap(str, 6, str.length() - 2));

Know P r ogr a m
Know P a ogr r m

Observe the code snippet, it has swapped the element in the 6th position ‘r’ with the element at the 10th position ‘a’ which is the length of the string – 2.

Here the swap() function is a user-defined function created for the user’s convenience. We will see the different ways to write this swap() method to swap characters in string Java.

How to Swap Two Characters in a String Java using toCharArray()

To swap two characters in a string in Java we can use the toCharArray() method available in the Java String class. Observe the below code, the swap is done between the first characters of each word that is 0th position is swapped with the 5th position. ‘K’ is swapped with ‘P’.

Читайте также:  Создать класс rectangle java

Program to Swap Two Characters in a String Java using toCharArray() Method

public class Main < public static char[] swap(String string, int i, int j) < char chr[] = string.toCharArray(); char temp = chr[i]; chr[i] = chr[j]; chr[j] = temp; return chr; >public static void main(String args[]) < String str = "Know Program"; System.out.println(str); System.out.println(swap(str, 0, 5)); >>

Swap Characters in String Java using substring()

Now, we will swap two characters in a string by using the substring() method. As we know the substring() method is a built-in method in java that returns a substring from the given string.

Program to Swap Characters in a String Java using substring()

public class Main < public static String swap(String string, int i, int j) < if (j == string.length() - 1) < return string.substring(0, i) + string.charAt(j) + string.substring(i + 1, j) + string.charAt(i); >return string.substring(0, i) + string.charAt(j) + string.substring(i + 1, j) + string.charAt(i)+ string.substring(j + 1, string.length()); > public static void main(String args[]) < String str = "Know Program"; System.out.println(str); System.out.println(swap(str, 0, 5)); >>

Swap Characters in String Java using StringBuilder

As we know the string is immutable which means we can not make any change once a string is created, on each and every modification a new String object will be created. Hence we can use the StringBuffer or StringBuilder class to modify the string elements. Now, let us see how to swap characters in string Java we will use StringBuilder Class.

Program to Swap Two Characters in a String Java Using StringBuilder

public class Main < static String stringSwap(String string, int i, int j) < StringBuilder sb = new StringBuilder(string); sb.setCharAt(i, string.charAt(j)); sb.setCharAt(j, string.charAt(i)); return sb.toString(); >public static void main(String args[]) < String str = "Know Program"; System.out.println(str); System.out.println(stringSwap(str, 0, 5)); >>

Observe all the above code works the same to swap characters in string Java but the methods and functions used are different.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

How to swap string characters in java?

Java provides several ways to swap characters in a String. Here are a few ways to do it, along with examples to help you understand the different methods.

Method 1: Using a char array

This method converts the String to a new character array, which can then be modified.

String input = "hello"; char[] inputArray = input.toCharArray();
  • Step 2 — Use a temporary variable to store the value of the first character, then replace the first character with the second character, and then the second character with the temporary variable

This will effectively swap the two characters.

char temp = inputArray[0]; inputArray[0] = inputArray[1]; inputArray[1] = temp;
String output = String.valueOf(inputArray);

At this point, the output would be «jello»

Method 2: Using the substring() and concatenation methods

String input = "hello"; String firstChar = input.substring(0, 1); String secondChar = input.substring(1, 2);
String output = secondChar + firstChar + input.substring(2);

At this point, the output would be «jello»

Method 3: Using the CharSequence interface and the append() method

  • Step 1 — Convert the String to a StringBuilder object, which is a class that implements the CharSequence interface

This allows you to use the append() method to change the characters within the String.

String input = "hello"; StringBuilder sb = new StringBuilder(input);
char temp = sb.charAt(0); sb.setCharAt(0, sb.charAt(1)); sb.setCharAt(1, temp);
String output = sb.toString();

At this point, the output would be «jello»

All the above methods, gives you a way to swap characters of a given string in Java. You can use any of the above method according to your convenience.

However, you should be mindful that, the above method only allow you to swap two characters. If you want to swap more than two characters, you will have to call these methods multiple times.

Sure, I can continue to explain more about the above methods and other ways to swap characters in a String in Java.

Another Method : Using the replace() method

String input = "hello"; StringBuilder sb = new StringBuilder(input);
char firstChar = input.charAt(0); char secondChar = input.charAt(1); int start = 0; int end = 1; sb.replace(start, end, Character.toString(secondChar)); sb.replace(start+1, end+1, Character.toString(firstChar));
String output = sb.toString();

You can use the above method in case of you have an index of characters you want to swap in the string.

All the above methods discussed are in-place swapping. Which means that the original input string is being modified. If you don’t want to modify the original string and create a new string instead, you can use any of the above methods and create a new string variable to store the output.

Conclusion

In conclusion, there are several ways to swap characters in a String in Java, including using a char array, substring() and concatenation, the CharSequence interface and the append() method, and the replace() method. Each of these methods has its own advantages and disadvantages, and the best method to use will depend on your specific use case. For example, if you’re working with a large string, using a char array and temporary variable might be more efficient than using the substring() and concatenation methods. On the other hand, the replace() method can be useful when you have an index of the characters you want to swap.

It is important to keep in mind that the methods described above are all in-place swapping, which means that the original input string is being modified. If you need to preserve the original string, make sure to create a new variable to store the output.

In summary, it’s recommended to understand the concept and performance of each method before choosing a method to swap the characters in a string.

Источник

How to Swap Two Strings in Java without Third Variable

The simple approach to swap two strings in Java is by using a third variable. But, we can also swap two strings without using the third variable.

Swap Two Strings in Java using Third Variable

Here is the simple program to swap two strings using a third variable.

package net.javastring.strings; public class JavaSwapStrings < public static void main(String[] args) < String s1 = "Apple"; String s2 = "Banana"; System.out.printf("Before Swapping s1 = %s and s2 = %s.\n", s1, s2); String temp = s1; s1 = s2; s2 = temp; System.out.printf("After Swapping s1 = %s and s2 = %s.\n", s1, s2); >>
Before Swapping s1 = Apple and s2 = Banana. After Swapping s1 = Banana and s2 = Apple.

Swap Two Strings in Java without Third Variable

The idea is to use String concatenation and then substring() method to swap two strings without using any third variable.

package net.javastring.strings; public class JavaSwapStrings < public static void main(String[] args) < String s1 = "Apple"; String s2 = "Banana"; System.out.println(String.format("Before Swapping s1 = %s and s2 = %s.\n", s1, s2)); s1 = s1 + s2; // s1 = "AppleBanana"; s2 = s1.substring(0, s1.length()-s2.length()); // s2 = "AppleBanana".substring(0, 11-6) = "Apple" s1 = s1.substring(s2.length()); // s1 = "AppleBanana".substring(5) = "Banana" System.out.println(String.format("After Swapping s1 = %s and s2 = %s.\n", s1, s2)); >>

Swap Two Strings In Java Without Third Variable

Notice the use of the String format() method. It works the same as System.out.printf() method.

References:

Источник

Swapping string in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью