TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
//在一个字符串中砍掉“空白和换行符”。
public class ChopWord{
public static final String chopAtWord(String string, int length) {
if (string == null) {
return string;
}
char [] charArray = string.toCharArray();
int sLength = string.length();
if (length < sLength) {
sLength = length;
}
// First check if there is a newline character before length; if so,
// chop word there.
for (int i=0; i<sLength-1; i++) {
// Windows
if (charArray == "
" && charArray[i+1] == "
") {
return string.substring(0, i+1);
}
// Unix
else if (charArray == "
") {
return string.substring(0, i);
}
}
// Also check boundary case of Unix newline
if (charArray[sLength-1] == "
") {
return string.substring(0, sLength-1);
}
// Done checking for newline, now see if the total string is less than
// the specified chop point.
if (string.length() < length) {
return string;
}
// No newline, so chop at the first whitespace.
for (int i = length-1; i > 0; i--) {
if (charArray == " ") {
return string.substring(0, i).trim();
}
}
// Did not find word boundary so return original String chopped at
// specified length.
return string.substring(0, length);
}
public static void main(String args[]){
String s1="abcdefg";
String s2="abc defg";
String s3="abcdefg
ijk";
String s4="abc
dddd";
String s5="ADDDDSC
kklss
ddd
";
System.out.println(chopAtWord(s1,6));
System.out.println(chopAtWord(s2,6));
System.out.println(chopAtWord(s3,6));
System.out.println(chopAtWord(s4,6));
System.out.println(chopAtWord(s5,10));
}
}
运行结果:
C:java>javac ChopWord.java
C:java>java ChopWord
abcdef
abc
abcdef
abc
ADDDDSC
源码下载:http://file.javaxxz.com/2014/9/30/214631469.zip |
|