问题描述:翻转一个字符串,并把小写变成大写 ,大写变成小写。
代码实现:
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[n] = '\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());
}
}