zoukankan      html  css  js  c++  java
  • Java字符串备忘录

    Java常量定义:

    final 数据类型 常量名 = 值;

    C++常量定义:

    const 数据类型 常量名 = 值;

    Java 中使用 String 类来定义一个字符串,字符串是常量,它们的值在创建之后不能更改。

    String s0 = "abc";

    String s1 = new String("abd");

    计算字符串长度:字符串标识符.length(); 

    例:

    String s1 = "abc";

    String s2 = "Java语言";

    int len1 = s1.length();

    int len2 = s2.length();

    比较字符串内容是否相同:equals();

    equals() 方法比较是从第一字符开始,一个字符一个字符依次比较。

    例:s1.equals(s2);

    如果想忽略掉大小写关系,可以调用 equalsIgnoreCase() 方法,其用法与 equals() 一致,不过它会忽视大小写。

    例:s1.equalsIgnoreCase(s2);

    比较字符串地址是否相同: "==" 比较的是两个对象在内存中存储的地址是否一样;

    例·:

    String s1 = "abc";

    String s2 = new String("abc");

    boolean b = (s1 == s2);

    则变量 b 的值是 false,因为 s1 对象对应的地址是 "abc" 的地址,而 s2 使用 new 关键字申请新的内存,所以内存地址和 s1 的 "abc" 的地址不一样,所以获得的值是 false

    字符串连接:

    字符串连接有两种方法:

    1. 使用 +,比如 String s = "Hello " + "World!"
    2. 使用 String 类的 concat() 方法。

    例:

    String s0 = new String("Hello ");

    String s1 = "World" + "!"; //+号连接

    String s2 = s0.concat(s1); //concat()方法连接

    System.out.println(s2);

    输出:Hello!World!

    获取字符串种某个字符:charAt()

    charAt() 方法的作用是按照索引值(规定字符串中第一个字符的索引值是 0,第二个字符的索引值是 1,依次类推),获得字符串中的指定字符。

    例:

    String s = "abc";

    char c = s.charAt(1);

    c输出的是b;

    字符串常用提取方法

    方法返回值功能描述
    indexOf(char ch) int 搜索字符 ch 第一次出现的索引
    indexOf(String value) int 搜索字符串 value 第一次出现的索引
    lastIndexOf(char ch) int 搜索字符 ch 最后一次出现的索引
    lastIndexOf(String value) int 搜索字符串 value 最后一次出现的索引
    substring(int index) String 提取从位置索引开始到结束的字符串
    substring(int beginindex, int endindex) String 提取 beginindex 和 endindex 之间的字符串部分
    trim() String 返回一个前后不含任何空格的调用字符串的副本
  • 相关阅读:
    arcsde 和oracle(双机热备)分布式安装(转载)
    ArcGIS Server分布式部署
    华为软件编程规范和范例(转载)
    常用Java开源库
    通过Word 2007发布Blog
    django中的models模块及数据库一些基本操作
    网页设计与后台程序解决方案模板引擎之Smarty
    Session 和 Cookie
    ul及li水平居中显示
    HTTP协议简介
  • 原文地址:https://www.cnblogs.com/knis/p/12838566.html
Copyright © 2011-2022 走看看