java.util.StringTokenizer Java Examples

The following examples show how to use java.util.StringTokenizer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestProcessor.java    From jclic with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: 11462 Age Sort.java    From UVA with GNU General Public License v3.0 6 votes vote down vote up
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());
	}
}
 
Example #3
Source File: QuestionInterpreter.java    From OpenEphyra with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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
		}
	}
}
 
Example #4
Source File: AbstractCompileMojo.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: MetadataFormatPrinter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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;
    }
}
 
Example #6
Source File: ClassSpellList.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: HttpHeaderTransport.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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;
}
 
Example #8
Source File: XMLSchemaLoader.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: FrameworkCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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;
}
 
Example #10
Source File: MonitorProgressObject.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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)+".*";
}
 
Example #11
Source File: 11172 Relational Operator.java    From UVA with GNU General Public License v3.0 6 votes vote down vote up
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('>');
		}
	}
}
 
Example #12
Source File: GlobalSettingChangeListener.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: JRELocaleProviderAdapter.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: XMLObject.java    From beast-mcmc with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @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);
}
 
Example #15
Source File: Task.java    From systemds with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #16
Source File: LocaleType.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
	}
}
 
Example #17
Source File: ColorParser.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * 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
  }
}
 
Example #18
Source File: ClassPathBuilder.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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));
    }
}
 
Example #19
Source File: SystemPermission.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #20
Source File: XMLSchedulingDataProcessorPlugin.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <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);         
    }
}
 
Example #21
Source File: Servlets.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 根据浏览器 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;
}
 
Example #22
Source File: DataCollectorBase.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
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 ) ;
    }
}
 
Example #23
Source File: ApisupportAntUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #24
Source File: MBeanServerPermission.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example #25
Source File: ItypeToken.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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;
}
 
Example #26
Source File: ProcessConfig.java    From KEEL with GNU General Public License v3.0 5 votes vote down vote up
/**
 * <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;
}
 
Example #27
Source File: EjbFacadeWizardPanel2.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #28
Source File: ZoneRec.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: ItemList.java    From EchoSim with Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example #30
Source File: SynthParser.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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));
}