Java Tutorial/Data Type/String Concatenation

Материал из Java эксперт
Перейти к: навигация, поиск

Padded String

/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. All rights reserved. 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 
Contributors:
2003 Erik Bengtson - moved replaceAll from Column class to here
2004 Andy Jefferson - moved intArrayToString, booleanArrayToString from SM
2007 Xuan Baldauf - toJVMIDString hex fix
    ...
**********************************************************************/

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
/**
 * Utilities for String manipulation.
 *
 * @version $Revision: 1.23 $   
 **/
public class StringUtils
{
  /** Utility to return a left-aligned version of a string padded to the
   * number of characters specified.
   * @param input The input string
   * @param length The length desired
   * @return The updated string 
   **/
  public static String leftAlignedPaddedString(String input,int length)
  {
      if (length <= 0)
      {
          return null;
      }
      StringBuffer output=new StringBuffer();
      char         space=" ";
      if (input != null)
      {
          if (input.length() < length)
          {
              output.append(input);
              for (int i=input.length();i<length;i++)
              {
                  output.append(space);
              }
          }
          else
          {
              output.append(input.substring(0,length));
          }
      }
      else
      {
          for (int i=0;i<length;i++)
          {
              output.append(space);
          }
      }
      return output.toString();
  }
  /** Utility to return a right-aligned version of a string padded to the
   * number of characters specified.
   * @param input The input string
   * @param length The length desired
   * @return The updated string 
   **/
  public static String rightAlignedPaddedString(String input,int length)
  {
      if (length <= 0)
      {
          return null;
      }
      StringBuffer output=new StringBuffer();
      char         space=" ";
      if (input != null)
      {
          if (input.length() < length)
          {
              for (int i=input.length();i<length;i++)
              {
                  output.append(space);
              }
              output.append(input);
          }
          else
          {
              output.append(input.substring(0,length));
          }
      }
      else
      {
          for (int i=0;i<length;i++)
          {
              output.append(space);
          }
      }
      return output.toString();
  }
}





Pad string

/*
 * Static String formatting and query routines.
 * Copyright (C) 2001-2005 Stephen Ostermiller
 * http://ostermiller.org/contact.pl?regarding=Java+Utilities
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * See COPYING.TXT for details.
 */

import java.util.HashMap;
import java.util.regex.Pattern;
/**
 * Utilities for String formatting, manipulation, and queries.
 * More information about this class is available from .
 *
 * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
 * @since ostermillerutils 1.00.00
 */
public class StringHelper {
  /**
   * Pad the beginning of the given String with spaces until
   * the String is of the given length.
   * 
   * If a String is longer than the desired length,
   * it will not be truncated, however no padding
   * will be added.
   *
   * @param s String to be padded.
   * @param length desired length of result.
   * @return padded String.
   * @throws NullPointerException if s is null.
   *
   * @since ostermillerutils 1.00.00
   */
  public static String prepad(String s, int length){
    return prepad(s, length, " ");
  }
  /**
   * Pre-pend the given character to the String until
   * the result is the desired length.
   * 
   * If a String is longer than the desired length,
   * it will not be truncated, however no padding
   * will be added.
   *
   * @param s String to be padded.
   * @param length desired length of result.
   * @param c padding character.
   * @return padded String.
   * @throws NullPointerException if s is null.
   *
   * @since ostermillerutils 1.00.00
   */
  public static String prepad(String s, int length, char c){
    int needed = length - s.length();
    if (needed <= 0){
      return s;
    }
    char padding[] = new char[needed];
    java.util.Arrays.fill(padding, c);
    StringBuffer sb = new StringBuffer(length);
    sb.append(padding);
    sb.append(s);
    return sb.toString();
  }
  /**
   * Pad the end of the given String with spaces until
   * the String is of the given length.
   * 
   * If a String is longer than the desired length,
   * it will not be truncated, however no padding
   * will be added.
   *
   * @param s String to be padded.
   * @param length desired length of result.
   * @return padded String.
   * @throws NullPointerException if s is null.
   *
   * @since ostermillerutils 1.00.00
   */
  public static String postpad(String s, int length){
    return postpad(s, length, " ");
  }
  /**
   * Append the given character to the String until
   * the result is  the desired length.
   * 
   * If a String is longer than the desired length,
   * it will not be truncated, however no padding
   * will be added.
   *
   * @param s String to be padded.
   * @param length desired length of result.
   * @param c padding character.
   * @return padded String.
   * @throws NullPointerException if s is null.
   *
   * @since ostermillerutils 1.00.00
   */
  public static String postpad(String s, int length, char c){
    int needed = length - s.length();
    if (needed <= 0){
      return s;
    }
    char padding[] = new char[needed];
    java.util.Arrays.fill(padding, c);
    StringBuffer sb = new StringBuffer(length);
    sb.append(s);
    sb.append(padding);
    return sb.toString();
  }
  /**
   * Pad the beginning and end of the given String with spaces until
   * the String is of the given length.  The result is that the original
   * String is centered in the middle of the new string.
   *
   * If the number of characters to pad is even, then the padding
   * will be split evenly between the beginning and end, otherwise,
   * the extra character will be added to the end.
   * 
   * If a String is longer than the desired length,
   * it will not be truncated, however no padding
   * will be added.
   *
   * @param s String to be padded.
   * @param length desired length of result.
   * @return padded String.
   * @throws NullPointerException if s is null.
   *
   * @since ostermillerutils 1.00.00
   */
  public static String midpad(String s, int length){
    return midpad(s, length, " ");
  }
  /**
   * Pad the beginning and end of the given String with the given character
   * until the result is  the desired length.  The result is that the original
   * String is centered in the middle of the new string.
   * 
   * If the number of characters to pad is even, then the padding
   * will be split evenly between the beginning and end, otherwise,
   * the extra character will be added to the end.
   *
   * If a String is longer than the desired length,
   * it will not be truncated, however no padding
   * will be added.
   *
   * @param s String to be padded.
   * @param length desired length of result.
   * @param c padding character.
   * @return padded String.
   * @throws NullPointerException if s is null.
   *
   * @since ostermillerutils 1.00.00
   */
  public static String midpad(String s, int length, char c){
    int needed = length - s.length();
    if (needed <= 0){
      return s;
    }
    int beginning = needed / 2;
    int end = beginning + needed % 2;
    char prepadding[] = new char[beginning];
    java.util.Arrays.fill(prepadding, c);
    char postpadding[] = new char[end];
    java.util.Arrays.fill(postpadding, c);
    StringBuffer sb = new StringBuffer(length);
    sb.append(prepadding);
    sb.append(s);
    sb.append(postpadding);
    return sb.toString();
  }
}





Return a string padded with the given string for the given count.

/*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */

public class Main{
  

  /////////////////////////////////////////////////////////////////////////
  //                            Padding Methods                          //
  /////////////////////////////////////////////////////////////////////////
  /**
   * Return a string padded with the given string for the given count.
   *
   * @param buff       String buffer used for padding (buffer is not reset).
   * @param string     Pad element.
   * @param count      Pad count.
   * @return           Padded string.
   */
  public static String pad(final StringBuffer buff, final String string,
     final int count)
  {
     for (int i = 0; i < count; i++)
     {
        buff.append(string);
     }
     return buff.toString();
  }
  /**
   * Return a string padded with the given string for the given count.
   *
   * @param string     Pad element.
   * @param count      Pad count.
   * @return           Padded string.
   */
  public static String pad(final String string, final int count)
  {
     return pad(new StringBuffer(), string, count);
  }
  /**
   * Return a string padded with the given string value of an object
   * for the given count.
   *
   * @param obj     Object to convert to a string.
   * @param count   Pad count.
   * @return        Padded string.
   */
  public static String pad(final Object obj, final int count)
  {
     return pad(new StringBuffer(), String.valueOf(obj), count);
  }
}





String concatenation: Combining a string and integers

public class MainClass {
  public static void main(String[] arg) {
    String myString = "fifty five is " + 5 + 5;
    System.out.println(myString);    
  }
}



fifty five is 55


String concatenation: Combining integers and a string

public class MainClass {
  public static void main(String[] arg) {
    String myString = 5 + 5 + " is ten";
    System.out.println(myString);   
  }
}



10 is ten


String concatenation: Convert an integer to String and join with two other strings

public class MainClass {
  public static void main(String[] arg) {
    int numHands = 99;
    
    String secondString = "secondString";
    String thirdString = "thirdString";
    
    String myString = numHands + " " + secondString + thirdString;
    System.out.println(myString);
  }
}



99 secondStringthirdString


String concatenation: "+" operation generates a new String object

public class MainClass {
  public static void main(String[] arg) {
    String myString = "String a" + " String b";
  
    System.out.println(myString);
  }
}



String a String b


String concatenation: The + contains null

public class MainClass {
  public static void main(String[] arg) {
    String myString = "String a" + null;
  
    System.out.println(myString);
  }
}



String anull


Substring replacement.

class StringReplace {
  public static void main(String args[]) {
    String org = "This is a test. This is, too.";
    String search = "is";
    String sub = "was";
    String result = "";
    int i;
    do { // replace all matching substrings
      System.out.println(org);
      i = org.indexOf(search);
      if (i != -1) {
        result = org.substring(0, i);
        result = result + sub;
        result = result + org.substring(i + search.length());
        org = result;
      }
    } while (i != -1);
  }
}