昨天参加了一个公司的笔试,题不是很难但是有很多我都没作对,所以基础还是薄弱了些。比如手写代码,看到这题完全慌了,其实很简单的题,但是临场发挥的很差,当时手写的很乱,但是回来用电脑都实现了。
有三道要操作字符串的题和一道关于File:
1、字符串每个单词首字母大写(默认单词之间有空格)。
2、把字母和数字用“_”分隔。
3、把单词之间有多个空格的调整为一个空格。
package com.lixin.project;
public class MakeStrUtil {
//1、将首字母大写
public static String getUWord(String string) {
String[] strings = string.split(" ");//取出每个单词
StringBuffer stringBuffer = new StringBuffer();
//取出单词首字母
for (int i = 0; i < strings.length; i++) {
//将首字母变为大写
String upCase = strings[i].substring(0, 1).toUpperCase();
//得到新的单词
String word = upCase + strings[i].substring(1, strings[i].length());
//放入StringBuffer容器中
stringBuffer.append(word+" ");
}
return new String(stringBuffer);
}
//2、把数字和字母用“_”分隔开
public static String splitWithSymbol(String string,String symbol) {
StringBuffer stringBuffer = new StringBuffer();
char[] chars = string.toCharArray();
stringBuffer.append(string.substring(0,1));
//遍历读取字符串
for (int i = 0; i < chars.length-1; i++) {
//按照char字符集编码判断字符是不是字母或数字或是符号,0~9:48~57,A~Z:65~90,a~z:97~122
String beforeLetter = string.substring(i,i+1);
String behindLetter = string.substring(i + 1, i + 2);
int temp1 = isNumOrLetter(beforeLetter);
int temp2 = isNumOrLetter(behindLetter);
if (temp1 != 0 && temp2 != 0 && temp1 != temp2) {
stringBuffer.append(symbol+behindLetter);
continue;
}
stringBuffer.append(behindLetter);
}
return new String (stringBuffer);
}
//3、把单词中间有多个空格的调整为1个空格
public static String delSpace(String string) {
StringBuffer stringBuffer = new StringBuffer();
char[] chars = string.toCharArray();
stringBuffer.append(string.substring(0,1));
//遍历读取字符串
for (int i = 0; i < chars.length-1; i++) {
//按照char字符集编码判断字符是不是字母或数字或是符号,0~9:48~57,A~Z:65~90,a~z:97~122
String beforeLetter = string.substring(i,i+1);
String behindLetter = string.substring(i + 1, i + 2);
if (" ".equals(beforeLetter)&&" ".equals(behindLetter)) {
continue;
}else {
stringBuffer.append(behindLetter);
}
}
return new String(stringBuffer);
}
public static int isNumOrLetter(String string) {
/**
* 返回正数则字符串为数字
* 返回0则字符串为符号
* 返回负数则字符串为字母
*/
int flag = 0;
int num = string.codePointAt(0);//前一个char字符编码
if (num >= 48 && num <= 57) {
//该字符为数字
flag = 1;
} else if (num >= 65 && num <= 90 || num >= 97 && num <= 122) {
//该字符为字母
flag = -1;
}
return flag;
}
//获取文件列表
public static void getFileName(String path) {
File f = new File(path);
if (!f.exists()) {
System.out.println(path + " not exists");
return;
}
File fa[] = f.listFiles();
for (int i = 0; i < fa.length; i++) {
File fs = fa[i];
if (fs.isDirectory()) {
System.out.println(fs.getName() + " [目录]");
} else {
System.out.println(fs.getName());
}
}
}
}
代码都亲测有效,这次亲手实现了,下次遇到这种题就不会出错了把。