早教吧 育儿知识 作业答案 考试题库 百科 知识分享

求帮写几个JAVA小程序!急急急!1)编程:检查输入的字符串是否是“回文”。(2)编程:字符串中删去所有重复的字符,每种字符只保留一个。(3)编程:统计一个字符串中给定字符串出

题目详情
求帮写几个JAVA小程序!急急急!
1)编程:检查输入的字符串是否是“回文”。
(2)编程:字符串中删去所有重复的字符,每种字符只保留一个。
(3)编程:统计一个字符串中给定字符串出现的频率。
(4)编程:将一个表示十进制数的字符串转换为以逗号分隔的字符串,从右边开始每三个数字标一个逗号。例如,给定一个字符串“1234567”,该方法返回“1,234,567”
▼优质解答
答案和解析

第一个不知道“回文”怎么理解,2,3,4都有了

package test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Test {

public static void main(String[] args) {
String str = "Hello,How are you?";
System.out.println(getPan(str));
System.out.println(getCount(str, 'l'));
System.out.println(change(1531858758));
}

/**
 * 字符串中删去所有重复的字符,每种字符只保留一个
 */
public static String getPan(String str) {
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < str.length(); i++) {
set.add(str.charAt(i));
}
String result = "";
Iterator<Character> it = set.iterator();
while (it.hasNext()) {
result = result + it.next();
}
return result;
}

/**
 * 统计一个字符串中给定字符串出现的频率
 */
public static int getCount(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count += 1;
}
}
return count;
}

/**
 * 将一个表示十进制数的字符串转换为以逗号分隔的字符串,从右边开始每三个数字标一个逗号
 */
public static String change(int count) {
int i;
String result = "";
for (i = 1; count > 0; i++) {
int a = count % 10;
if (i % 3 == 0) {
result = "," + a + result;
} else {
result = a + result;
}
count = count / 10;
}
i = i - 1;
if (i % 3 == 0) {
return result.substring(1);
} else {
return result;
}
}
}