题目
字符串的调整与替换
java代码
package com.lizhouwei.chapter5;
/**
* @Description: 字符串的调整与替换
* @Author: lizhouwei
* @CreateDate: 2018/4/24 22:13
* @Modify by:
* @ModifyDate:
*/
public class Chapter5_10 {
public String repalce(char[] chars) {
int len = 0;
int num = 0;
for (len = 0; len < chars.length && chars[len] != 0; len++) {
if (chars[len] == ' ') {
num++;
}
}
int j = len + 2 * num - 1;
for (int i = len - 1; i > -1; i--) {
if (chars[i] != ' ') {
chars[j--] = chars[i];
} else {
chars[j--] = '0';
chars[j--] = '2';
chars[j--] = '%';
}
}
return String.valueOf(chars);
}
public String modify(char[] chars) {
int j = chars.length - 1;
for (int i = chars.length - 1; i > -1; i--) {
if (chars[i] != '*') {
chars[j--] = chars[i];
}
}
for (; j > -1; j--) {
chars[j] = '*';
}
return String.valueOf(chars);
}
//测试
public static void main(String[] args) {
Chapter5_10 chapter = new Chapter5_10();
char[] str = new char[100];
str[0] = 'a';
str[1] = ' ';
str[2] = 'b';
str[3] = ' ';
str[4] = ' ';
str[5] = 'c';
String result = chapter.repalce(str);
System.out.println("字符串 a b c 替换空格后为:" + result);
char[] str2 = {'*', '1', '2', '*', '3', '*'};
String result2 = chapter.modify(str2);
System.out.println("字符串{'*','1','2','*','3','*'}调整后为:" + result2);
}
}
结果