📄 stringtools.java
字号:
/*
StringTools: Miscellaneous static methods for dealing with Strings.
copyright (c) 1997-2008 Roedy Green, Canadian Mind Products
may be copied and used freely for any purpose but military.
Roedy Green
Canadian Mind Products
#101 - 2536 Wark Street
Victoria, BC Canada
V8T 4G8
tel: (250) 361-9093
roedy g at mindprod dotcom
http://mindprod.com
version history
version 1.5 2005-07-14 split off from Misc, allow for compilation with old compiler.
version 1.6 2006-10-15 add condense method.
version 1.7 2006-03-04 format with IntelliJ and prepare Javadoc
version 1.9 2008-03-10 add StringTools.firstWord
*/
package com.mindprod.common11;
import java.awt.Color;
/**
* Miscellaneous static methods for dealing with Strings.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.9 2008-03-10 add StringTools.firstWord
* @since 2003-05-15
*/
public final class StringTools
{
// ------------------------------ FIELDS ------------------------------
/**
* true if you want extra debugging output and test code
*/
private static final boolean DEBUGGING = false;
// -------------------------- PUBLIC STATIC METHODS --------------------------
/**
* makeshift system beep if awt.Toolkit.beep is not available. Works also in JDK 1.02.
*/
public static void beep()
{
System.out.print( "\007" );
System.out.flush();
}// end beep
/**
* Convert String to canonical standard form. null -> "". Trims lead trail blanks.
*
* @param s String to be converted.
* @return String in canonical form.
*/
public static String canonical( String s )
{
if ( s == null )
{
return "";
}
else
{
return s.trim();
}
}// end canonical
/**
* Collapse multiple spaces in string down to a single space. Remove lead and trailing spaces.
*
* @param s String to strip of blanks.
* @return String with all blanks, lead/trail/embedded removed.
* @noinspection WeakerAccess,SameParameterValue
* @see #squish(String)
*/
public static String condense( String s )
{
if ( s == null )
{
return null;
}
s = s.trim();
if ( s.indexOf( " " ) < 0 )
{
return s;
}
int len = s.length();
// have to use StringBuffer for JDK 1.1
StringBuffer b = new StringBuffer( len - 1 );
boolean suppressSpaces = false;
for ( int i = 0; i < len; i++ )
{
char c = s.charAt( i );
if ( c == ' ' )
{
if ( suppressSpaces )
{
// subsequent space
}
else
{
// first space
b.append( c );
suppressSpaces = true;
}
}
else
{
// was not a space
b.append( c );
suppressSpaces = false;
}
}// end for
return b.toString();
}// end condense
/**
* Count how many times a String occurs on a page.
*
* @param page big String to look in.
* @param lookFor small String to look for and count instances.
* @return number of times the String appears non-overlapping.
*/
public static int countInstances( String page, String lookFor )
{
int count = 0;
for ( int start = 0;
( start = page.indexOf( lookFor, start ) ) >= 0;
start += lookFor.length() )
{
count++;
}
return count;
}
/**
* count of how many leading characters there are on a string matching a given character. It does not remove them.
*
* @param text text with possible leading characters, possibly empty, but not null.
* @param c the leading character of interest, usually ' ' or '\n'
* @return count of leading matching characters, possibly 0.
* @noinspection WeakerAccess
*/
public static int countLeading( String text, char c )
{
// need defined outside the for loop.
int count;
for ( count = 0; count < text.length()
&& text.charAt( count ) == c; count++ )
{
}
return count;
}
/**
* count of how many trailing characters there are on a string matching a given character. It does not remove them.
*
* @param text text with possible trailing characters, possibly empty, but not null.
* @param c the trailing character of interest, usually ' ' or '\n'
* @return count of trailing matching characters, possibly 0.
* @noinspection WeakerAccess
*/
public static int countTrailing( String text, char c )
{
int length = text.length();
// need defined outside the for loop.
int count;
for ( count = 0; count < length
&& text.charAt( length - 1 - count ) == c; count++ )
{
}
return count;
}
/**
* gets the first word of a String, delimited by space or the end of the string.
*
* @param s the input String
* @return the first word of the String.
*/
public static String firstWord( String s )
{
int place = s.indexOf( ' ' );
return ( place < 0 ) ? s : s.substring( 0, place );
}
/**
* find the first instance of whitespace (space, \n, \r, \t in a string.
*
* @param s string to scan
* @return -1 if not found, offset relative to start of string where found
*/
public static int indexOfWhiteSpace( String s )
{
return indexOfWhiteSpace( s, 0 );
}
/**
* find the first instance of whitespace (space, \n, \r, \t in a string.
*
* @param s string to scan
* @param startOffset where in string to start looking
* @return -1 if not found, offset relative to start of string where found, not relative to startOffset.
*/
public static int indexOfWhiteSpace( String s, int startOffset )
{
final int length = s.length();
for ( int i = startOffset; i < length; i++ )
{
switch ( s.charAt( i ) )
{
case ' ':
case '\n':
case '\r':
case '\t':
return i;
default:
// keep looking
}
}// end for
return -1;
}
/**
* Is this string empty? In Java 1.6 + isEmpty is build in. Sun's version being an instance method cannot test for
* null.
*
* @param s String to be tested for emptiness.
* @return true if the string is null or equal to the "" null string. or just blanks
*/
public static boolean isEmpty( String s )
{
return ( s == null ) || s.trim().length() == 0;
}// end isEmpty
/**
* Ensure the string contains only legal characters.
*
* @param candidate string to test.
* @param legalChars characters than are legal for candidate.
* @return true if candidate is formed only of chars from the legal set.
*/
public static boolean isLegal( String candidate, String legalChars )
{
for ( int i = 0; i < candidate.length(); i++ )
{
if ( legalChars.indexOf( candidate.charAt( i ) ) < 0 )
{
return false;
}
}
return true;
}
/**
* Check if char is plain ASCII lower case.
*
* @param c char to check.
* @return true if char is in range a..z.
* @see Character#isLowerCase(char)
*/
public static boolean isUnaccentedLowerCase( char c )
{
return 'a' <= c && c <= 'z';
}// isUnaccentedLowerCase
/**
* Check if char is plain ASCII upper case.
*
* @param c char to check.
* @return true if char is in range A..Z.
* @see Character#isUpperCase(char)
*/
public static boolean isUnaccentedUpperCase( char c )
{
return 'A' <= c && c <= 'Z';
}// end isUnaccentedUpperCase
/**
* Pads the string out to the given length by applying blanks on the left.
*
* @param s String to be padded/chopped.
* @param newLen length of new String desired.
* @param chop true if Strings longer than newLen should be truncated to newLen chars.
* @return String padded on left/chopped to the desired length. Spaces are inserted on the left.
*/
public static String leftPad( String s, int newLen, boolean chop )
{
int grow = newLen - s.length();
if ( grow <= 0 )
{
if ( chop )
{
return s.substring( 0, newLen );
}
else
{
return s;
}
}
else if ( grow <= 30 )
{
return " ".substring( 0, grow ) + s;
}
else
{
return rep( ' ', grow ) + s;
}
}// end leftPad
/**
* convert a String to a long. The routine is very forgiving. It ignores invalid chars, lead trail, embedded spaces,
* decimal points etc. Dash is treated as a minus sign.
*
* @param numStr String to be parsed.
* @return long value of String with junk characters stripped.
* @throws NumberFormatException if the number is too big to fit in a long.
*/
public static long parseDirtyLong( String numStr )
{
numStr = numStr.trim();
// strip commas, spaces, decimals + etc
StringBuffer b = new StringBuffer( numStr.length() );
boolean negative = false;
for ( int i = 0; i < numStr.length(); i++ )
{
char c = numStr.charAt( i );
if ( c == '-' )
{
negative = true;
}
else if ( '0' <= c && c <= '9' )
{
b.append( c );
}
}// end for
numStr = b.toString();
if ( numStr.length() == 0 )
{
return 0;
}
long num = Long.parseLong( numStr );
if ( negative )
{
num = -num;
}
return num;
}// end parseDirtyLong
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -