Swap string in java

How to swap String characters in Java?

Given string str , the task is to write a Java program to swap the pairs of characters of a string. In this article we would go through some methods to swap character of a given String and get a new String (with swapped characters) while the original String remains unaffected.

How to swap String characters in Java?

How can I swap two characters in a String ? For example, «abcde» will become «bacde» .

Since String objects are immutable, going to a char[] via toCharArray , swapping the characters, then making a new String from char[] via the String(char[]) constructor would work.

The following example swaps the first and second characters:

String originalString = "abcde"; char[] c = originalString.toCharArray(); // Replace with a "swap" function, if desired: char temp = c[0]; c[0] = c[1]; c[1] = temp; String swappedString = new String(c); System.out.println(originalString); System.out.println(swappedString); 

‘In’ a string, you cant. Strings are immutable. You can easily create a second string with:

 String second = first.replaceFirst("(.)(.)", "$2$1"); 

This has been answered a few times but here’s one more just for fun 🙂

public class Tmp < public static void main(String[] args) < System.out.println(swapChars("abcde", 0, 1)); >private static String swapChars(String str, int lIdx, int rIdx) < StringBuilder sb = new StringBuilder(str); char l = sb.charAt(lIdx), r = sb.charAt(rIdx); sb.setCharAt(lIdx, r); sb.setCharAt(rIdx, l); return sb.toString(); >> 
static String string_swap(String str, int x, int y) < if( x < 0 || x >= str.length() || y < 0 || y >= str.length()) return "Invalid index"; char arr[] = str.toCharArray(); char tmp = arr[x]; arr[x] = arr[y]; arr[y] = tmp; return new String(arr); > 

Swap — Swapping a specific character in a char array, it has been 8 years since I last programmed, and then it was just basics for a networking degree. I am writing a basic program to start my way …

Читайте также:  Center align button

Swapping Characters of a String in Java

As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created).
To do modifications on string stored in a String object, we copy it to a Character array, StringBuffer, etc and do modifications on the copy object.
In this article we would go through some methods to swap character of a given String and get a new String (with swapped characters) while the original String remains unaffected.
Through the examples below lets see some of the method by which we can swap character an generate new String
Examples:
Method 1 (Using toCharArray)
In this method we convert the String into the Character array and perform the required Swapping.

Java

geeksfkrgeeos seeksforgeekg geeksforgeeks

Method 2 (Using subString())
We build the modified string using substrings of given string.

Java

geeksfkrgeeos seeksforgeekg geeksforgeeks

Method 3 (Using StringBuilder or StringBuffer)
In this method either you can use StringBuilder or StringBuffer depending on the situation. See String vs StringBuilder vs StringBuffer in Java to decide when to use which one.

Java

geeksfkrgeeos seeksforgeekg geeksforgeeks
geeksfkrgeeos seeksforgeekg geeksforgeeks

This article is contributed by Sumit Ghosh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Java — How can I swap Characters in a string, I wrote this bit of code to swap characters in a word but for some reason its not swapping the first Character, any help will be appreciated.

Swapping Characters in a String in Java

Given the above excerpt from a Java code, I need to modify the code such that it could recursively swap pairs of the content of the string variable, «locationAddress». Please note that the variable, «locationAddress», contains a string of characters, say, abcdefghij. I wish to swap «abcdefghij» in pairs such that the result will be «badcfehgji».

Please kindly assist with the necessary modification to the above Java code excerpt to make it recursively swap pairs of characters in the string variable, «locationAddress».

public void format(DataObject dataSource) throws Exception < String locationAddress = dataSource.getValueAsString("Location-Address").substring(4); if (dataSource.parameterExists("Location-Address")) < dataSource.setParameter("Parameter-Type","400"); dataSource.setParameter("Parameter-Value", locationAddress); >> 

Here is a very simple way to do this using regex replacement in Java:

String input = "abcdefghij"; input = input.replaceAll("(.)(.)", "$2$1"); System.out.println(input); badcfehgji 

The idea is to walk down the string, starting at the beginning, capturing two characters at a time, in two different capture groups. Then, just swap those two captured characters in the replacement.

Here’s one solution with StringBuilder :

public static String swapAdjacentPairs(String s) < StringBuilder sb = new StringBuilder(s); // divide 2 and then multiply by 2 to handle cases where the string length is odd // we always want an even string length // also note the i += 2 for (int i = 0 ; i < (s.length() / 2 * 2) ; i += 2) < swapAdjacent(sb, i); >return sb.toString(); > private static void swapAdjacent(StringBuilder sb, int index)
System.out.println(swapAdjacentPairs("abcdefghi")); 
String input = "abcdefghijk"; String swapped = IntStream.range(0, input.length()) .map(i -> i % 2 == 0 ? i == input.length() - 1 ? i : i + 1 : i - 1) .mapToObj(input::charAt) .map(String::valueOf) .collect(Collectors.joining()); System.out.println(swapped); // badcfehgjik 

The swapping is driven by the index i . If i is even and there is a next ( i+1 ) character then it’s used. If i is odd then the previous ( i-1 ) character is used.

Java — Swap two letters in a string, After reading through some the other answers, a new version, that doesn’t just work in Java 8, works with replacing characters which need to be …

Swapping Pairs of Characters in a String in Java

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.

Input: str = “Java”

Output: aJva

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.

1. Using String.toCharArray() Method

  1. Get the string to swap a pair of characters.
  2. Check if the string is null or empty then return the string.
  3. Converting the given string into a character array.
  4. Traverse the character array and swap the characters.
  5. Now, print the result.

Источник

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.

Источник

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