首页 > 技术文章 > JAVA操作字符串

qinxu 2018-01-04 15:01 原文

package com.test;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *JAVA字符串操作
 */
public class StringTest {

    private static final Logger logger = LoggerFactory.getLogger(StringTest.class);
    /**
     * 删除最后一位字符串
     */
    @Test
    public void deleteStr(){
        String str = "123456789*";
        //用的最多的是Substring
        logger.debug(str.substring(0,str.length()-1));
    }

    /**
     * 截取指定字符串
     */
    @Test
    public void cutOutStr(){
        String str = "hello world";
        //截取hello
        logger.debug(str.substring(str.lastIndexOf("h"),str.lastIndexOf(" ")));
        //去掉第一位 
        logger.debug(str.substring(1));
        //截取指定位数
        logger.debug(str.substring(1,7));
    }
    /**
     *字符串替换
     */
    @Test
    public void operateStr(){
        String str = "123";
        logger.debug(str.replace("12","22"));
    }
  /**
   *字符串去掉\
   */
  @Test
  public void RemoveStr(){
  String str = "Hello World \"";
  str = str.replaceAll("\\\\","");
  System.out.println(str);
  }

  /**
  *字符长度
  *
  */
  @Test
  public  int getStrLength(String str){
  str = str.replaceAll("[^\\x00-\\xff]", "**");
       return str.length;
    } }

 

推荐阅读