zoukankan      html  css  js  c++  java
  • string 字符串 的一些使用方法

    Java语言中,把字符串作为对象来处理,类String就可以用来表示字符串(类名首字母都是大写的)。

    字符串常量是用双引号括住的一串字符。

    例如:"Hello World"

    String表示字符串变量

    String用来可以创建字符串对象,String使用示例:

    1 String s=new String() ;   //生成一个空串
    2 String s1="Hello World"; //声明s1为字符串"Hello World"的引用

    1  String s1="a";
    2  String s2="a";
    3  s1+="b";
    4  System.out.println(s1=="ab");         // false
    5  System.out.println(s1==s2+"b");     // false
    6  System.out.println(s2=="a");           // true
    7  System.out.println(s1.equals("ab")); // true
    8  System.put.println(new String("ab")==new String("ab"));  // false

    以下几点需要注意:

      • 在Java中,内容相同的字串常量(“a”)只保存一份以节约内存,所以s1,s2实际上引用的是同一个对象。
      • 编译器在编译s1一句时,会去掉“+”号,直接把两个字串连接起来得一个字串(“ab”)。这种优化工作由Java编译器自动完成。
      • 当直接使用new关键字创建字符串对象时,虽然值一致(都是“ab”),但仍然是两个独立的对象。

    访问字符串

          类String中提供了length( )、charAt( )、indexOf( )、lastIndexOf( )、getChars( )、getBytes( )、toCharArray( )等方法。

    public int length() 此方法返回字符串的字符个数     

    public char charAt(int index) 此方法返回字符串中index位置上的字符,其中index 值的 范围是0~length-1     

    public int indexOf(int ch)     public lastIndexOf(in ch)  返回字符ch在字符串中出现的第一个和最后一个的位置

    public int indexOf(String str)   public int lastIndexOf(String str)  返回子串str中第一个字符在字符串中出现的第一个和最后一个的位置

    public int indexOf(int ch,int fromIndex)   public lastIndexOf(in ch ,int fromIndex)  返回字符ch在字符串中位置fromIndex以后出现的第一个和最后一个的位置

    public int indexOf(String str,int fromIndex)   public int lastIndexOf(String str,int fromIndex)  返回子串str中的第一个字符在字符串中位置fromIndex后出现的第一个和最后一个的位置。

    public void getchars(int srcbegin,int end ,char buf[],int dstbegin)  srcbegin 为要提取的第一个字符在源串中的位置, end为要提取的最后一个字符在源串中的位置,字符数组buf[]存放目的字符串,dstbegin 为提取的字符串在目的串中的起始位置。

    public void getBytes(int srcBegin, int srcEnd,byte[] dst, int dstBegin)  参数及用法同上,只是串中的字符均用8位表示。

    5、修改字符串,参考java API。

    String类提供的方法:

    concat( )

    replace( )

    substring( )

    toLowerCase( )

    toUpperCase( )

    public String contat(String str);  用来将当前字符串对象与给定字符串str连接起来。

    public String replace(char oldChar,char newChar);  用来把串中出现的所有特定字符替换成指定字符以生成新串。

    public String substring(int beginIndex);   public String substring(int beginIndex,int endIndex);  用来得到字符串中指定范围内的子串。

    public String toLowerCase();  把串中所有的字符变成小写。

    public String toUpperCase();  把串中所有的字符变成大写。

  • 相关阅读:
    linux 相关( 随时更新)
    django admin 修改批量操作内容
    区块链
    关于读取excel 和 写excel
    git基本用法
    服务器与本地的控制工具unison
    爬虫框架 Scrapy
    爬虫高性能 asyncio库 twisted库 tornado库
    爬虫请求库之selenium模块
    爬虫请求库
  • 原文地址:https://www.cnblogs.com/Zf451452043/p/6009044.html
Copyright © 2011-2022 走看看