下面列出了怎么用java.util.StringTokenizer的API类实例代码及写法,或者点击链接到github查看源代码。
public static String toNbsp(String src) {
StringBuilder sb = new StringBuilder(src == null ? 0 : src.length() * 2);
if (src != null) {
StringTokenizer st = new StringTokenizer(src);
if (st.hasMoreTokens()) {
while (true) {
sb.append(st.nextToken());
if (st.hasMoreTokens()) {
sb.append(" ");
} else {
break;
}
}
}
}
return sb.substring(0);
}
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=br.readLine())!=null) {
int N=Integer.parseInt(s);
if (N==0) {
break;
}
int [] ints=new int [N];
StringTokenizer st=new StringTokenizer(br.readLine());
for (int i=0;i<ints.length;i++) {
ints[i]=Integer.parseInt(st.nextToken());
}
Arrays.sort(ints);
StringBuilder sb=new StringBuilder();
for (int i=0;i<ints.length;i++) {
sb.append(ints[i]);
if (i<ints.length-1) {
sb.append(" ");
}
}
System.out.println(sb.toString());
}
}
/**
* Adds the keywords in a descriptor of a question pattern to the dictionary
* for the respective PROPERTY.
*
* @param expr pattern descriptor
* @param prop PROPERTY the question pattern belongs to
*/
private static void addKeywords(String expr, String prop) {
// tokenize expr, delimiters are meta-characters, '<', '>' and blank
StringTokenizer st = new StringTokenizer(expr, "\\|*+?.^$(){}[]<> ");
String token;
HashDictionary dict;
while (st.hasMoreTokens()) {
token = st.nextToken();
if (token.length() > 2 && !FunctionWords.lookup(token)) {
// token has a length of at least 3 and is not a function word
dict = keywords.get(prop);
if (dict == null) { // new dictionary
dict = new HashDictionary();
keywords.put(prop, dict);
}
dict.add(token); // add token to the dictionary
}
}
}
private static Set<Debug> parseDebug(String debug) {
Set<Debug> result = new HashSet<AbstractCompileMojo.Debug>();
StringTokenizer st = new StringTokenizer(debug, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken();
Debug keyword;
if ("true".equalsIgnoreCase(token)) {
keyword = Debug.all;
} else if ("false".equalsIgnoreCase(token)) {
keyword = Debug.none;
} else {
keyword = Debug.valueOf(token);
}
result.add(keyword);
}
if (result.size() > 1 && (result.contains(Debug.all) || result.contains(Debug.none))) {
throw new IllegalArgumentException("'all' and 'none' must be used alone: " + debug);
}
return result;
}
private void printWrapped(String in, int leftIndent) {
StringTokenizer t = new StringTokenizer(in);
while (t.hasMoreTokens()) {
String s = t.nextToken();
int length = s.length();
if (column + length > maxColumn) {
println();
indent();
for (int i = 0; i < leftIndent; i++) {
print(" ");
}
}
out.print(s);
out.print(" ");
column += length + 1;
}
}
/**
* Lists never have a Type, so this returns false
*/
@Override
public boolean isType(String type)
{
if ((type.isEmpty()) || (types == null))
{
return false;
}
//
// Must match all listed types in order to qualify
//
StringTokenizer tok = new StringTokenizer(type, ".");
while (tok.hasMoreTokens())
{
if (!types.contains(Type.getConstant(tok.nextToken())))
{
return false;
}
}
return true;
}
Map<String, String> parse(String serialized) {
final StringTokenizer pairTokenizer = new StringTokenizer(serialized.trim(), ",");
final Map<String, String> context = new HashMap<>();
while (pairTokenizer.hasMoreTokens()) {
final String pairStr = pairTokenizer.nextToken();
final String[] keyValuePair = pairStr.split("=");
if (keyValuePair.length != 2) {
continue;
}
try {
final String key = URLDecoder.decode(keyValuePair[0], ENCODING_CHARSET);
final String value = URLDecoder.decode(keyValuePair[1], ENCODING_CHARSET);
context.put(key, value);
} catch (UnsupportedEncodingException e) {
LOGGER.error("Charset not found", e);
}
}
return context;
}
public static boolean tokenizeSchemaLocationStr(String schemaStr, Map locations) {
if (schemaStr!= null) {
StringTokenizer t = new StringTokenizer(schemaStr, " \n\t\r");
String namespace, location;
while (t.hasMoreTokens()) {
namespace = t.nextToken ();
if (!t.hasMoreTokens()) {
return false; // error!
}
location = t.nextToken();
LocationArray la = ((LocationArray)locations.get(namespace));
if(la == null) {
la = new LocationArray();
locations.put(namespace, la);
}
la.addLocation(location);
}
}
return true;
}
private Set<String> getAllFrameworkPropKeys()
{
final HashSet<String> res = new HashSet<String>();
// Keys of properties mentioned in the OSGi specification.
res.addAll(FW_PROP_NAMES);
// All available keys from a property maintained by the
// Knopflerfish Framework implementation for this purpose.
final String fwPropKeys = bc.getProperty(fwPropKeysKey);
if (null!=fwPropKeys) {
final StringTokenizer st = new StringTokenizer(fwPropKeys,",");
while (st.hasMoreTokens()) {
final String key = st.nextToken().trim();
res.add(key);
}
}
return res;
}
private String getNameToQuery(String name) {
if (name.indexOf('.') == -1) {
return name+".*";
}
StringTokenizer st = new StringTokenizer(name, ".");
String newName = "";
int segment = 0;
int nameSegment = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
segment++;
if (token.length() > newName.length()) {
newName = token;
nameSegment = segment;
}
}
return (nameSegment > 1 ? "*."+newName : newName)+".*";
}
public static void main (String [] abc) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int testCaseCount = Integer.parseInt(br.readLine());
for (int i=0;i<testCaseCount;i++) {
StringTokenizer st=new StringTokenizer(br.readLine());
int x=Integer.parseInt(st.nextToken());
int y=Integer.parseInt(st.nextToken());
if (x<y) {
System.out.println('<');
} else if (x==y) {
System.out.println('=');
} else {
System.out.println('>');
}
}
}
/**
* Returns the list of favored player toons.
*
* @return the list of favored player toons
*/
private static List< Toon > getFavoredToonList() {
final List< Toon > list = new ArrayList<>();
final StringTokenizer st = new StringTokenizer( Env.APP_SETTINGS.get( Settings.FAVORED_PLAYER_TOONS ), "," );
while ( st.hasMoreTokens() ) {
String toon = null;
try {
toon = st.nextToken().trim();
if ( !toon.isEmpty() )
list.add( new Toon( toon ) );
} catch ( final IllegalArgumentException iae ) {
// Invalid toon, ignore it (but log warning)
Env.LOGGER.warning( "Invalid toon in the Favored Player list: " + toon, iae );
}
}
return list;
}
protected Set<String> createLanguageTagSet(String category) {
String supportedLocaleString = LocaleDataMetaInfo.getSupportedLocaleString(category);
if (supportedLocaleString == null) {
return Collections.emptySet();
}
Set<String> tagset = new HashSet<>();
StringTokenizer tokens = new StringTokenizer(supportedLocaleString);
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
if (token.equals("|")) {
if (isNonENLangSupported()) {
continue;
}
break;
}
tagset.add(token);
}
return tagset;
}
/**
* @return the object as an double[] if possible
*/
private String[] getStringArray(Object obj) throws XMLParseException {
if (obj instanceof String[]) return (String[]) obj;
if (obj instanceof String) {
ArrayList<String> stringList = new ArrayList<String>();
StringTokenizer st = new StringTokenizer((String) obj);
while (st.hasMoreTokens()) {
stringList.add(st.nextToken());
}
String[] strings = new String[stringList.size()];
for (int i = 0; i < strings.length; i++) {
strings[i] = stringList.get(i);
}
return strings;
}
throw new XMLParseException("Expected array of strings, but got " + obj);
}
public static Task parseCompactString( String stask )
{
StringTokenizer st = new StringTokenizer( stask.trim(), "." );
TaskType type = TaskType.valueOf(st.nextToken());
String meta = st.nextToken();
Task newTask = new Task(meta, type);
//iteration data
String sdata = st.nextToken();
sdata = sdata.substring(1,sdata.length()-1); // remove brackets
StringTokenizer st2 = new StringTokenizer(sdata, ",");
while( st2.hasMoreTokens() ) {
//create new iteration
String lsdata = st2.nextToken();
IntObject ldata = new IntObject(Integer.parseInt(lsdata));
newTask.addIteration(ldata);
}
return newTask;
}
public Object fromStringValue(String string) {
if (string == null) {
return null;
}
else {
StringTokenizer tokens = new StringTokenizer(string, "_");
String language = tokens.hasMoreTokens() ? tokens.nextToken() : "";
String country = tokens.hasMoreTokens() ? tokens.nextToken() : "";
// Need to account for allowable '_' within the variant
String variant = "";
String sep = "";
while ( tokens.hasMoreTokens() ) {
variant += sep + tokens.nextToken();
sep = "_";
}
return new Locale(language, country, variant);
}
}
/**
* Parses the hidden.
*
* @param token the token
* @param sme the sme
*/
// test for "hidden:true" or false
private void parseHidden(StringTokenizer token, StyleMapEntry sme) {
if (token.hasMoreTokens()) {
String ck = token.nextToken(); // checked
String tf = token.nextToken(); // true or false
if (ck.equals("hidden")) {
boolean checked = false;
if (tf.equals("true")) {
checked = true;
}
sme.setHidden(checked);
}
} else {
sme.setHidden(Boolean.FALSE); // Default to not hidden
}
}
/**
* Add worklist items from given system classpath.
*
* @param workList
* the worklist
* @param path
* a system classpath
*/
private void addWorkListItemsForClasspath(LinkedList<WorkListItem> workList, String path) {
if (path == null) {
return;
}
StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
while (st.hasMoreTokens()) {
String entry = st.nextToken();
if (DEBUG) {
System.out.println("System classpath entry: " + entry);
}
addToWorkList(workList, new WorkListItem(classFactory.createFilesystemCodeBaseLocator(entry), false,
ICodeBase.Discovered.IN_SYSTEM_CLASSPATH));
}
}
/**
* Return a canonical form of the passed in actions.
* Actions are lower-cased, in the order of LEGAL_ACTIONS
* and on;ly appear once.
*/
private static String getCanonicalForm(String actions) {
actions = actions.trim().toLowerCase(Locale.ENGLISH);
boolean[] seenAction = new boolean[LEGAL_ACTIONS.size()];
StringTokenizer st = new StringTokenizer(actions, ",");
while (st.hasMoreTokens()) {
String action = st.nextToken().trim().toLowerCase(Locale.ENGLISH);
int validAction = LEGAL_ACTIONS.indexOf(action);
if (validAction != -1)
seenAction[validAction] = true;
}
StringBuilder sb = new StringBuilder();
for (int sa = 0; sa < seenAction.length; sa++)
{
if (seenAction[sa]) {
if (sb.length() != 0)
sb.append(",");
sb.append(LEGAL_ACTIONS.get(sa));
}
}
return sb.toString();
}
/**
* <p>
* Called during creation of the <code>Scheduler</code> in order to give
* the <code>SchedulerPlugin</code> a chance to initialize.
* </p>
*
* @throws org.quartz.SchedulerConfigException
* if there is an error initializing.
*/
public void initialize(String name, final Scheduler scheduler, ClassLoadHelper schedulerFactoryClassLoadHelper)
throws SchedulerException {
super.initialize(name, scheduler);
this.classLoadHelper = schedulerFactoryClassLoadHelper;
getLog().info("Registering Quartz Job Initialization Plug-in.");
// Create JobFile objects
StringTokenizer stok = new StringTokenizer(fileNames, FILE_NAME_DELIMITERS);
while (stok.hasMoreTokens()) {
final String fileName = stok.nextToken();
final JobFile jobFile = new JobFile(fileName);
jobFiles.put(fileName, jobFile);
}
}
/**
* 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
*
* 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
*
* @param etag 内容的ETag.
*/
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!"*".equals(headerValue)) {
StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(etag)) {
conditionSatisfied = true;
}
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeaders.ETAG, etag);
return false;
}
}
return true;
}
private void setProperty( String name, String value )
{
if( name.equals( ORBConstants.ORB_INIT_REF_PROPERTY ) ) {
// Value is <name>=<URL>
StringTokenizer st = new StringTokenizer( value, "=" ) ;
if (st.countTokens() != 2)
throw new IllegalArgumentException() ;
String refName = st.nextToken() ;
String refValue = st.nextToken() ;
resultProps.setProperty( name + "." + refName, refValue ) ;
} else {
resultProps.setProperty( name, value ) ;
}
}
/**
* Check whether a given path can serve as a legal <ol>
* <li>File path name
* </ol>
*/
public static boolean isValidFilePath(String name) {
if (name.length() == 0) {
return false;
}
name = name.substring(0, name.lastIndexOf("."));
StringTokenizer tk = new StringTokenizer(name,"/",true); //NOI18N
boolean delimExpected = false;
while (tk.hasMoreTokens()) {
String namePart = tk.nextToken();
if (delimExpected ^ namePart.equals("/")) { // NOI18N
return false;
}
if (!delimExpected && !Utilities.isJavaIdentifier(namePart)) {
return false;
}
delimExpected = !delimExpected;
}
return delimExpected;
}
private static int parseMask(String name) {
/* Check that target name is a non-null non-empty string */
if (name == null) {
throw new NullPointerException("MBeanServerPermission: " +
"target name can't be null");
}
name = name.trim();
if (name.equals("*"))
return ALL_MASK;
/* If the name is empty, nameIndex will barf. */
if (name.indexOf(',') < 0)
return impliedMask(1 << nameIndex(name.trim()));
int mask = 0;
StringTokenizer tok = new StringTokenizer(name, ",");
while (tok.hasMoreTokens()) {
String action = tok.nextToken();
int i = nameIndex(action.trim());
mask |= (1 << i);
}
return impliedMask(mask);
}
@Override
protected ParseResult parseTokenWithSeparator(LoadContext context, EquipmentModifier mod, String value)
{
context.getObjectContext().removeList(mod, ListKey.ITEM_TYPES);
StringTokenizer tok = new StringTokenizer(value, Constants.DOT);
while (tok.hasMoreTokens())
{
final String typeName = tok.nextToken();
if ("double".equalsIgnoreCase(typeName))
{
return new ParseResult.Fail(
"IType must not be double. Ignoring occurrence in " + getTokenName() + Constants.COLON + value);
}
else
{
context.getObjectContext().addToList(mod, ListKey.ITEM_TYPES, Type.getConstant(typeName));
}
}
return ParseResult.SUCCESS;
}
/**
* <p>
* Sets the class member dataTable3 with the next tokens in configuration file.
* </p>
* @param tokens tokens recover class connected to the configuration file.
* @throws SyntaxError
*/
void doDataTable3(StringTokenizer tokens) throws SyntaxError {
if (!tokens.hasMoreTokens()) {
throw new SyntaxError("Elección de la tabla 3 no especificada");
}
String tmp = tokens.nextToken();
while (!tmp.equals("=")) {
tmp = tokens.nextToken();
}
tmp = tokens.nextToken();
dataTable3 = tmp;
}
private static boolean isValidPackageName(String str) {
if (str.length() > 0 && str.charAt(0) == '.') { //NOI18N
return false;
}
StringTokenizer tukac = new StringTokenizer(str, "."); //NOI18N
while (tukac.hasMoreTokens()) {
String token = tukac.nextToken();
if ("".equals(token)) { //NOI18N
return false;
} else if (!Utilities.isJavaIdentifier(token)) {
return false;
}
}
return true;
}
/**
* Parses a Zone text line that is described by a StringTokenizer.
* @param tokens represents tokens of a Zone text line
* @return the zone record produced by parsing the text
*/
static ZoneRec parse(StringTokenizer tokens) {
ZoneRec rec = new ZoneRec();
try {
rec.gmtOffset = (int) Time.parse(tokens.nextToken()).getTime();
String token = tokens.nextToken();
char c = token.charAt(0);
if (c >= '0' && c <= '9') {
rec.directSave = (int) Time.parse(token).getTime();
} else {
rec.ruleName = token;
}
rec.format = tokens.nextToken();
if (tokens.hasMoreTokens()) {
rec.hasUntil = true;
rec.untilYear = Integer.parseInt(tokens.nextToken());
if (tokens.hasMoreTokens()) {
rec.untilMonth = Month.parse(tokens.nextToken());
} else {
rec.untilMonth = Month.JANUARY;
}
if (tokens.hasMoreTokens()) {
rec.untilDay = RuleDay.parse(tokens.nextToken());
} else {
rec.untilDay = new RuleDay(1);
}
if (tokens.hasMoreTokens()) {
rec.untilTime = Time.parse(tokens.nextToken());
} else {
rec.untilTime = Time.parse("0:00");
}
rec.untilInMillis = rec.getLocalUntilTime();
}
} catch (Exception e) {
// TODO: error reporting
e.printStackTrace();
}
return rec;
}
public void split(String s,String sp,List append,boolean isMultiToken){
if(s==null || sp==null)
return;
if(isMultiToken){
StringTokenizer tokens=new StringTokenizer(s,sp);
while(tokens.hasMoreTokens()){
append.add(tokens.nextToken().trim());
}
}
else{
this.split(s,sp,append);
}
}
/**
* Convenience method to return an Insets object.
*/
private Insets parseInsets(String insets, String errorMsg) throws
SAXException {
StringTokenizer tokenizer = new StringTokenizer(insets);
return new Insets(nextInt(tokenizer, errorMsg),
nextInt(tokenizer, errorMsg),
nextInt(tokenizer, errorMsg),
nextInt(tokenizer, errorMsg));
}