您的位置:首页 > 编程语言 > Java开发

java字符串翻转

2016-04-20 10:51 381 查看
问题描述:翻转一个字符串,并把小写变成大写 ,大写变成小写。

代码实现:

package leetcoder;
import java.util.*;

public class Solution1 {
public static String trans(String s, int n) {
if (s == null)
return null;
char[] ch = new char[n + 1];
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'z')
ch[i] = (char) (c - 32);
else if (c >= 'A' && c <= 'Z')
ch[i] = (char) (c + 32);
else
ch[i] = c;
}
ch
= '\0';
int i = 0, j = s.length() - 1;
while (i < j) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
i++;
j--;
}
i = 0;
j = 0;
while (j != n + 1 && i != n + 1) {
if (ch[i] == ' ') {
i++;
j++;
} else if (ch[j] == ' ' || ch[j] == '\0') {
int tempj = j;
int tempi = i;
--tempj;
while (tempi < tempj) {
char temp = ch[tempi];
ch[tempi] = ch[tempj];
ch[tempj] = temp;
tempi++;
tempj--;
}
i = ++j;
} else {
j++;
}
}
String str = new String(ch);
return str;
}
public static void main(String[] args) {
String s = "      This is a simple";
System.out.println(trans(s, s.length()).toString());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: