Java String Sanitize sanitizeName(String origName)

Here you can find the source of sanitizeName(String origName)

Description

Produce a sanitized name that fits our standards for likely to work.

License

Open Source License

Declaration

static public String sanitizeName(String origName) 

Method Source Code

//package com.java2s;
/**/*w  ww .j  av a  2 s  .com*/
 * Copyright (c) 2010 Ben Fry and Casey Reas
 *
 * 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.opensource.org/licenses/eclipse-1.0.php
 */

public class Main {
    /**
     * Produce a sanitized name that fits our standards for likely to work.
     * <p/>
     * Java classes have a wider range of names that are technically allowed
     * (supposedly any Unicode name) than what we support. The reason for
     * going more narrow is to avoid situations with text encodings and
     * converting during the process of moving files between operating
     * systems, i.e. uploading from a Windows machine to a Linux server,
     * or reading a FAT32 partition in OS X and using a thumb drive.
     * <p/>
     * This helper function replaces everything but A-Z, a-z, and 0-9 with
     * underscores. Also disallows starting the sketch name with a digit.
     */
    static public String sanitizeName(String origName) {
        char c[] = origName.toCharArray();
        StringBuffer buffer = new StringBuffer();

        // can't lead with a digit, so start with an underscore
        if ((c[0] >= '0') && (c[0] <= '9')) {
            buffer.append('_');
        }
        for (int i = 0; i < c.length; i++) {
            if (((c[i] >= '0') && (c[i] <= '9')) || ((c[i] >= 'a') && (c[i] <= 'z'))
                    || ((c[i] >= 'A') && (c[i] <= 'Z'))) {
                buffer.append(c[i]);

            } else {
                buffer.append('_');
            }
        }
        // let's not be ridiculous about the length of filenames.
        // in fact, Mac OS 9 can handle 255 chars, though it can't really
        // deal with filenames longer than 31 chars in the Finder.
        // but limiting to that for sketches would mean setting the
        // upper-bound on the character limit here to 25 characters
        // (to handle the base name + ".class")
        if (buffer.length() > 63) {
            buffer.setLength(63);
        }
        return buffer.toString();
    }
}

Related

  1. sanitizeName(String input)
  2. SanitizeName(String Name)
  3. sanitizeName(String name)
  4. sanitizeName(String name)
  5. sanitizeName(String name)
  6. sanitizeNamespace(String namespace)
  7. sanitizeOperationId(String operationId)
  8. sanitizePackageName(String raw)
  9. sanitizePackageVersion(String string)