Sure, here is an example program in Java that swaps two characters in a string:
public class StringSwapExample {
public static void main(String[] args) {
String str = "Hello World";
System.out.println("Before swap: " + str);
// Swap characters at positions 1 and 4
str = swapCharacters(str, 1, 4);
System.out.println("After swap: " + str);
}
public static String swapCharacters(String str, int pos1, int pos2) {
// Convert the string to a character array
char[] charArray = str.toCharArray();
// Swap the characters at the specified positions
char temp = charArray[pos1];
charArray[pos1] = charArray[pos2];
charArray[pos2] = temp;
// Convert the character array back to a string
return new String(charArray);
}
}
In this program, we first define a string "Hello World" and print it out. Then we call the
swapCharacters
method to swap the characters at positions 1 and 4 (which are 'e' and 'o', respectively) and store the result back in the original string variable.The
swapCharacters
method takes a string, and two integer positions to swap. It converts the string to a character array, swaps the characters at the specified positions using a temporary variable, and then converts the character array back to a string and returns it.
nice blog. keep posting sir
ReplyDelete