题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
解题思路:
1、倒序遍历字符串,反正添加进来,同时通过判断大小写,来反正大小写
这里要注意的是,stringbuffer.append()时,添加char要强转,不然会变成数字
2、stringbuffer有reverse和replace字符串的函数。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param n int整型
* @return string字符串
*/
public String trans (String s, int n) {
// if(n ==0) {
// return "";
// }
StringBuffer res = new StringBuffer();
for(int i=n-1; i>=0; i--) {
char temp = s.charAt(i);
//这里要特别小心,字符串要强转append
if(temp <='Z' && temp>= 'A') {
res.append((char)(temp - 'A' + 'a'));
} else if(temp <='z' && temp>='a') {
res.append((char)(temp - 'a'+ 'A'));
} else {
res.append(temp);
}
}
String ress = res.toString();
for(int i=0; i<n; i++) {
int j=i;
while(j<n && res.charAt(j)!=' ') {
j++;
}
String word = res.substring(i, j);
StringBuffer buf = new StringBuffer(word);
String replace = buf.reverse().toString();
res.replace(i, j, replace);
i = j;
}
return res.toString();
}
}
