集册 Java实例教程 获取一个普通字符串并将其转换为适合URL中标题的内容。

获取一个普通字符串并将其转换为适合URL中标题的内容。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

338
接受一个普通的字符串并将其转换为适合URL中标题的内容。


//package com.nowjava;//时代Java - nowjava.com


public class Main {

    /**

     * Takes a normal string and turns it into something suitable for a title in a URL.

     * This is all about SEO.  Basically, spaces go to dash and anything that isn't

     * URL-friendly gets stripped out.

     */

    public static String makeTitle(String title) {

        if (title == null)

            return "";


        StringBuilder bld = new StringBuilder();


        for (int i = 0; i < title.length(); i++) {

            char ch = title.charAt(i);
/**N o w J a v a . c o m - 时代Java**/

            if (Character.isWhitespace(ch))

                bld.append('-');

            else if (Character.isLetterOrDigit(ch))

                bld.append(ch);


            // otherwise skip

        }


        // Strip out any extra -'s that might get generated

        String dedup = bld.toString().replaceAll("-+", 
展开阅读全文