您的位置:首页 > 其它

字符串测试题1

2016-05-21 15:57 148 查看
用java语言实现两个函数encode()和decode(),分别实现对字符串的变换和复原.变换函数encode()顺序考察已知字符串的字符,按以下规则逐组生成新字符串:

(1)若已知字符串的当前字符不是大于0的数字字符,则复制该字符于新字符串中;

(2)若已知字符串的当前字符是一个数字字符,且它之后没有后继字符,则简单地将它复制到新字符串中;

(3)若已知字符串的当前字符是一个大于0的数字字符,并且还有后继字符,设该数字字符的面值为n,则将它的后继字符(包括后继字符是一个数字字符)重复复制n+1次到新字符串中;

(4)以上述一次变换为一组,在不同组之间另插入一个下划线'_'用于分隔;

(5)若已知字符串中包含有下划线'_',则变换为 ”\UL” 。

例如:encode()函数对字符串24ab_2t2的变换结果为 444_aaaaa_a_b_\UL_ttt_t_2

复原函数decode()做变换函数encode()的相反的工作.按照上述规则逆运算,变回原来的字符串。

public class ZiFuChuan {

// 转换方法
public void encode(String str) {
String st = "";
for (int i = 0; i < str.length(); i++) {
if ((str.charAt(i) >= '0' && str.charAt(i) <= '9') && (i + 1) == str.length()) {
st = st + str.charAt(i);
} else if ((str.charAt(i) >= '1' && str.charAt(i) <= '9') && (i + 1) != str.length()) {
int num1 = str.charAt(i) - 48;
String ls = "";
for (int j = 0; j <= num1; j++) {
ls = ls + str.charAt(i + 1);
}
st += ls + "_";
} else if (str.charAt(i) == '_') {
st += '\\' + "UL" + "_";
} else {
if (i != str.length() - 1) {
st += str.charAt(i) + "_";
}
if (i == str.length() - 1) {
st += str.charAt(i);
}
}
}
System.out.println("变换后:" + st);
}

// 还原方法
public void decode(String str) {
String st = "";
int count = 0;
String arr[] = str.split("_");
for (int i = 0; i < arr.length; i++) {
if (arr[i].length() == 1) {
st += arr[i];
} else if (arr[i].equals('\\' + "UL")) {
st += "_";
} else if (arr[i].length() > 1 && arr[i] != ('\\' + "UL")) {
st += arr[i].length() - 1;
} else if (arr[i].isEmpty()) {
count++;
if (!arr[i + 1].isEmpty()) {
st = st + (count - 2);
}
}
}
System.out.println("还原后的字符串:" + st);
}

public static void main(String[] args) {
Scanner sc1 = new Scanner(System.in);
System.out.println("请输入要转换的字符串:");
String str1 = sc1.nextLine();
ZiFuChuan z1 = new ZiFuChuan();
z1.encode(str1);

Scanner sc2 = new Scanner(System.in);
System.out.println("请输入要还原的字符串:");
String str2 = sc2.nextLine();
ZiFuChuan z2 = new ZiFuChuan();
z2.decode(str2);

}

}


运行结果:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: