首页 / JAVA / 在java中的字符串中交换几个字符?
在java中的字符串中交换几个字符?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在java中的字符串中交换几个字符?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2339字,纯文字阅读大概需要4分钟。
内容图文
![在java中的字符串中交换几个字符?](/upload/InfoBanner/zyjiaocheng/733/2effc003d4da47beb6f4875e0751c7b4.jpg)
我需要处理一个字符串来交换几个字符以进行简单加密.
Input : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Output: NOPQRSTUVWXYZABCDEFGHIJKLM
在上面的过程中,我将字符串分成两部分,并将前半部分移动到后半部分.
final int mid = (xyz.length()+1) / 2;
String[] spstr = {
xyz.substring(0, mid),
xyz.substring(mid),
};
String firstMix=spstr[1]+spstr[0];
System.out.println(firstMix);
现在,我需要将前两个字符与最后两个字符交换
Input : NOPQRSTUVWXYZABCDEFGHIJKLM
Output: LMPQRSTUVWXYZABCDEFGHIJKNO
并且还会立即将两个字符交换到字符串中间的左侧,并紧跟其后的两个字符.
Input : LMPQRSTUVWXYZABCDEFGHIJKNO
Output : LMPQRSTUVWXABYZCDEFGHIJKNO
交换发生在关于输入和输出的“YZAB”到“ABYZ”之间
有效交换这些字符的最佳方法是什么?我会在这个过程中转换很多字符串.在这种情况下,字符串长度不是常量.
解决方法:
这是大致正确的,除了将字符串长度上的中间字符交换为奇数的未定义情况.注释应该足以理解代码.
public class Main {
public static void main( String[] args ) {
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
final int mid = ( chars.length + 1 ) / 2;
System.out.println( "Mid: " + mid );
System.out.println( "Start : " + new String( chars ) );
// Pass one : Swap first half chars with last half chars
if( ( chars.length % 2 ) == 1 ) {
/* We swap the characters this way because the left half
* is one character longer than the right half. To avoid
* unnecessary copies we move the right character to
* the index before the left character and save the first
* character to be placed at the mid point
*/
char first = chars[ 0 ];
for( int l = 1, r = mid; r < chars.length; l++, r++ ) {
chars[ l - 1 ] = chars[ r ];
chars[ r ] = chars[ l ];
}
chars[ mid - 1 ] = first;
}
else {
for( int l = 0, r = mid; r < chars.length; l++, r++ ) {
swap( chars, l, r );
}
}
System.out.println( "Pass 1: " + new String( chars ) );
// Pass two: Swap first two chars with last two chars
swap( chars, 0, chars.length - 2 );
swap( chars, 1, chars.length - 1 );
System.out.println( "Pass 2: " + new String( chars ) );
// Pass three: Swap middle 4 characters.
swap( chars, mid - 1, mid + 1 );
swap( chars, mid - 2, mid );
System.out.println( "Pass 3: " + new String( chars ) );
}
public static void swap( char[] chars, int l, int r ) {
char tmp = chars[ l ];
chars[ l ] = chars[ r ];
chars[ r ] = tmp;
}
}
我选择使用字符数组进行操作以减少创建的对象数量.在我看来,这为您所要求的提供了最快捷的解决方案.当/如果你澄清未定义的情况我可以编辑代码以提供正确的输出.
内容总结
以上是互联网集市为您收集整理的在java中的字符串中交换几个字符?全部内容,希望文章能够帮你解决在java中的字符串中交换几个字符?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。