zoukankan      html  css  js  c++  java
  • 字符串拆分与截取

    范例:实现字符串的拆分处理

    全拆分

    String str = "hello world hello mldn";

    String result [] = str.split(" ");

    for(int x = 0 ; x < result.length ; x++)

    {

      System.out.println(result[x]);

    }

    部分拆分

    String str = "hello world hello mldn";

    String result [] = str.split(" ",2);

    for(int x = 0 ; x < result.length ; x++)

    {

      System.out.println(result[x]);

    }

    拆分ip地址

    String str = "192.168.1.1";

    String result [] = str.split("\.");   如果发现有些拆分不了,需使用\进行拆分

    for(int x = 0 ; x < result.length ; x++)

    {

      System.out.println(result[x]);

    }

    String str = "SMITH:10 | ALLEN :20";

    String result [] = str.split("\|");   如果发现有些拆分不了,需使用\进行拆分

    for(int x = 0 ; x < result.length ; x++)

    {

      String temp [] = result[x].split(":");

      System.out.println(temp[0] + " = " + temp[1]);

    }

    字符串截取

    完整的字符串中截取部分内容

    String str = "helloworld";

    System.out.println(str.substring(5));  // world

     System.out.println(str.substring(0,5));  // hello

    范例:观察trim()方法的使用

    去掉字符串中左右的空格 保留中间空格

    String str1 = "helloworld";

    String str2 = "hello".contat("world");               // 

    System.out.println(str1 == str2);                   // false

    System.out.println(str1 == str2.intern());       // true

    System.out.println(str2);       // helloworld

    范例:观察isEmpty()方法

    Syetem.out.println("hello".isEmpty());            //false

    Syetem.out.println("".isEmpty());    //true

    Syetem.out.println(new String().isEmpty());  //true

    范例:实现首字母大写

    String name = "smith";

    System.out.println(initcap(name));

    public  static String initcap(String str)

    {

      if(str == null || "".equals(str))

      {

        return str ;

      }

      if(str.length()>1)

      {

        return str.substring(0,1).toUpperCase() + str.substring(1);

      } 

      return str.UpperCase();

    }

  • 相关阅读:
    fzu 2138
    hdu 1598 暴力+并查集
    poj 1734 floyd求最小环,可得到环上的每个点
    floyd求最小环 模板
    fzu 2087并查集的运用求最小生成树的等效边
    hdu 2586 lca在线算法(朴素算法)
    CF 602 D. Lipshitz Sequence 数学 + 单调栈 + 优化
    Problem 2238 Daxia & Wzc's problem 1627 瞬间移动
    D. Tavas and Malekas DFS模拟 + kmp + hash || kmp + hash
    K-th Number 线段树的区间第K大
  • 原文地址:https://www.cnblogs.com/123talents/p/7466929.html
Copyright © 2011-2022 走看看