zoukankan      html  css  js  c++  java
  • 字符串

    如何使用字符串 ?

    一 .定义字符串的三种方式:

    1.String  s="Hello  World" ;
    2.String  s=new  String ;
    3.String  s=new String("Hello  World") ;

    使用字符串分为两种:

    1. 定义并初始化字符串

    2. 使用字符串进行一些处理。

    语法:

    创建一个字符串对象"Hello  world";

    String   s="Hello   world";

    在Java中,字符串被认作为String类型的对象来处理

    String类是设计人员预先提供的一个非常有用的类。

    创建String对象另外两种

    //创建一个空的字符串

    String  s=new   String( );

    或者

    //创建一个字符串对象"Hello   world"

    String  s=new   String("Hello   world");

    字符串的长度

    语法:

    字符串1.length( );

    3.比较两个字符串的值:

    1. equals( )方法可以比较两个字符串的值,

    如:      a.equals(scb);

    equals方法( )会对两个字符串变量中的值中的每一个字符一一比较,如果每个字符都相等,则为true反之为false

    如: a==b

    ==方法中比较的是两个字符串的内存首地址,如果两个字符串的内存首地址匹配,则返回true反之为false

    4.equalsIgnoreCase( )方法可以忽略英文字母大小写

    例如 : a.equalsIgnoreCase(b);

    toLowerCase( )方法可以将字符串中的英文字母转换为小写

     ( )方法可以将字符串的英文字母转换为大写

    6.字符串的连接:

    1.使用“+”’号来拼接字符串,可以将多个字符串拼接为一个新的字符串。

    在使用“+”运算符连接字符串和 int(double)类型的数据时,“+”将int(double)类型数据自动转换成String类型

    例如:  a.concat(b);

    字符串方法:

    1.indexOf( )方法;

    该方法是在字符串内搜索某个指定的位置的字符串,它返回出现的第一个匹配字符的位置。

    String s="青春无悔";
    int index=s.indexOf('春');

    执行后,返回值“春”的位置是1.

    2.      lastlndexOf()方法

    该方法也是在字符串内搜索某个指定的字符串但是它是搜索最后一个出现的字符(或字符串)的位置。

    String s="青春无悔";

    int index=s.lastIndexOF("青春");

    执行后,返回字符串,“青春”的首字符位置,index的值为6

    3.     Subtring(int  index)方法

    String  s="青春无悔";

    String  result=s.subString(1);

    4.    Subtring(int  beginindex,int  endindex)方法

    String s="青春无悔无悔青春";

    String  result =s.substring(2,6);

    5.     trim( )方法

     带方法可以忽略字符串前后的空格。

    字符串的拆分:

    语法:字符串1.split(String  separator,int  limit);

    (1) separator 可选项,标识拆分字符串时使用一个或多个字符,如果不选择该项,则返回值包含该字符串的所有单个字符的元素数组。

    (2)limit可选项,该值用来限制返回数组中的元素个数。

    示例:

    public  class void{
    String word;
    }
    public class Lyric{
    public static void  main(String[]args){
    String  words="长亭外  古道边  芳草碧连天  晚风扶  柳笛声残  夕阳山外";
    String []word=new String[100];   //定义接收数组
    System.out.print("****原歌词形式*****
    +words");
    System.out.print("
    *****拆分后歌词格式******");
    word =words.split(" ");       //按照空格拆分
    for(int  i=0;i<word.length;i++){
    System.out.print(word[i]);    //打印输出
                     }
              }
        }
  • 相关阅读:
    【leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal
    【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal
    【leetcode】236. Lowest Common Ancestor of a Binary Tree
    【leetcode】235. Lowest Common Ancestor of a Binary Search Tree
    【leetcode】352. Data Stream as Disjoint Intervals
    【leetcode】897. Increasing Order Search Tree
    【leetcode】900. RLE Iterator
    BEC listen and translation exercise 26
    BEC listen and translation exercise 25
    BEC listen and translation exercise 24
  • 原文地址:https://www.cnblogs.com/864466244qq/p/7376027.html
Copyright © 2011-2022 走看看