Add brackets ( '(' and ')' ) around source when it contains any white space characters. - Java java.lang

Java examples for java.lang:String Contain

Description

Add brackets ( '(' and ')' ) around source when it contains any white space characters.

Demo Code

/*******************************************************************************
 * Copyright (c) 2009 Ordina and committers to Mod4j
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*  w  ww  .  j  av a2s .  c  o m*/
 *     Jos Warmer & Anneke Kleppe - initial implementation taken from Octopus
 *     Ordina - initial implementation
 *******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String source = "java2s.com";
        System.out.println(addBrackets(source));
    }

    /**
     * Add brackets ( '(' and ')' ) around <code>source</code> when it contains any white space characters.
     * 
     * @param source
     * @return
     */
    static public String addBrackets(String source) {
        String temp = source;
        temp = temp.trim(); // remove all whitespace from begin and end
        if (temp.charAt(0) == '(' && temp.charAt(temp.length() - 1) == ')') {
            return source;
        } else if (source.indexOf(' ') != -1) { // string contains a space character
            source = "(" + source + ")";
        }
        return source;
    }
}

Related Tutorials