In a string of gaps and remove newline
Abstract: In a string of gaps and remove newline
</ Td> </ tr> <tr> <td width="467" height="35" valign="top" class="ArticleTeitle"> ↑ Back Tags: java string, String
/ / Cut off in a string of "gaps and newline."
(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
If (charArray [i] == '\ r' & charArray [i +1] == '\ n') (
Return string.substring (0, i +1);
)
/ / Unix
Else if (charArray [i] == '\ n') (
Return string.substring (0, i);
)
)
/ / Also check boundary case of Unix newline
If (charArray [sLength-1] == '\ n') (
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 [i] == '') (
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 \ nijk";
String s4 = "abc \ r \ ndddd";
String s5 = "ADDDDSC \ nkklss \ nddd \ n";
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));
)
)
The result:
C: \ java> javac ChopWord.java
C: \ java> java ChopWord
Abcdef
Abc
Abcdef
Abc
ADDDDSC
</ Td> <td width="217" align="center" valign="top" class="ArticleTeitle">
</ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">
Releated Java Articles
Comments
Leave a Reply






