1.将一个字符串逆序输出 例如: abcd --> dcba
public static void main(String[] args) {
String s1 = "abcd";
char[] c = s1.toCharArray();
char[] a = new char[4];
int j =3;
for (int i = 0; i < c.length; i++) {
a[j--] = c[i];
}
String s2 = new String(a);
System.out.println(a);
}
2.统计一个字符串中出现的大写字母,小写字母各自的个数
public static void main(String[] args) {
System.out.println("请输入一串字母(含大小写):");
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
char[] c = s1.toCharArray();
int small = 0;
int large = 0;
for (int i = 0; i < s1.length(); i++) {
if(c[i]>='A' && c[i]<='Z'){
large++;
}else if(c[i]>='a' && c[i]<='z'){
small++;
}
}
System.out.println("大写字母个数:"+large);
System.out.println("小写字母个数:"+small);
}
3.判断一个字符串是否对称,例如"abccba"
public static void Symmetric(String s1){
char[] c = s1.toCharArray();
int len = c.length;
int count = c.length - 1;
boolean flag=false;
for (int i = 0; i < (c.length-1)/2; i++) {
if(c[i] != c[count--]){
flag=false;
break;
}
}
if(flag){
System.out.println("对称");
}else {
System.out.println("不对称");
}
}
public static void main(String[] args) {
System.out.println("输入一串字符串:");
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
Symmetric(s1);
}
4.定义一个用于截取文件后缀名的方法, 传入一个字符串的文件名( hello.java),返回一个字符串.
public static void main(String[] args) {
System.out.println("请输入一个字符串的文件名:");
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
char[] c1 = s1.toCharArray();
char[] c2 = new char[20];
int j = 0;
for (int i = 0; i < s1.length(); i++) {
if(c1[i]=='.'){
for (int k = 0; k < s1.length(); k++) {
k = ++i;
c2[j++] = c1[k];
}
}
}
String s2 = new String(c2);
System.out.println("文件后缀名为:"+s2);