JavaSE第十节————认识String类

系列文章目录

JavaSE第十节————认识String类

认识String类

  1. 认识 String 类
  2. 了解 String 类的基本用法
  3. StringBuilder和StringBuffer
  4. String类练习题

文章目录


一、认识 String 类

在C语言中已经涉及到字符串了,但是在C语言中要表示字符串只能使用字符数组或者字符指针,可以使用标准库提供的字符串系列函数完成大部分操作,但是这种将数据和操作数据方法分离开的方式不符合面相对象的思想,而字符串应用又非常广泛,因此Java语言专门提供了String类。
在开发和校招笔试中,字符串也是常客,比如:
字符串转整形数字
字符串相加
而且在面试中也频繁被问到,比如:String、StringBuff和StringBulider之间的区别等

二、了解 String 类的基本用法

1. 字符串构造

    public static void main(String[] args) {
// 使用常量串构造
        String s1 = "hello bit";//""双引号引起来的叫字符常量,并且没有\0来标记结尾
        System.out.println(s1);//String重写了toString方法所以没有打印s1的地址
// 直接newString对象
        String s2 = new String("hello bit");
        System.out.println(s1);
// 使用字符数组进行构造
        char[] array = {'h','e','l','l','o','b','i','t'};
        String s3 = new String(array);
        System.out.println(s1);
    }

【注意】

1. String类实例变量

String是引用类型,内部并不存储字符串本身,在String类的实现源码中,String类实例变量如下
在这里插入图片描述

 public static void main(String[] args) {
// s1和s2引用的是不同对象 s1和s3引用的是同一对象
        String s1 = new String("hello");
        String s2 = new String("world");
        String s3 = s1;
       // String s4 = null;//它不指向任何对象
        System.out.println(s1.length()); // 获取字符串长度---输出5
        System.out.println(s1.isEmpty()); // 如果字符串长度为0,返回true,否则返回false
       // System.out.println(s4.isEmpty()); // 空指针异常
    }

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  1. 在Java中“”引起来的也是String类型对象。
// 打印"hello"字符串(String对象)的长度
System.out.println("hello".length());

2.String对象的比较( * * *

字符串的比较是常见操作之一,比如:字符串排序。Java中总共提供了4中方式:

1. ==比较是否引用同一个对象

字符串的比较是常见操作之一,比如:字符串排序。
==比较是否引用同一个对象(地址是否相同)
注意:对于内置类型,= = 比较的是变量中的值;对于引用类型 = =比较的是引用中的地址。
内置类型

    public static void main(String[] args) {
        int a = 156;
        int b = 22;
        int c = 156;
// 对于基本类型变量,==比较两个变量中存储的值是否相同
        System.out.println(a == b); // false
        System.out.println(a == c); // true

    }

在这里插入图片描述

引用类型

    public static void main(String[] args) {
        // 对于引用类型变量,==比较是否引用同一个对象(地址是否相同)
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("world");
        String s4 = s1;
        System.out.println(s1 == s2); // false
        System.out.println(s2 == s3); // false
        System.out.println(s1 == s4); // true

    }

在这里插入图片描述

2. boolean equals(Object anObject) 方法

按照字典序比较(用于比较两个字符串是否相等)
字典序:字符大小的顺序
String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照
如下规则进行比较,比如: s1.equals(s2)
编译器自带的equals

    public boolean equals(Object anObject) {
        // 1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
        if (this == anObject) {
            return true;
        }
        // 2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
        if (anObject instanceof String) {
            // 将anObject向下转型为String类型对象
            String anotherString = (String) anObject;
            int n = value.length;
            // 3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                // 4. 按照字符顺序,从前往后逐个字符进行比较
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3 = new String("Hello");
// s1、s2、s3引用的是三个不同对象,因此==比较结果全部为false
        System.out.println(s1 == s2); // false
        System.out.println(s1 == s3); // false
// equals比较:String对象中的逐个字符
// 虽然s1与s2引用的不是同一个对象,但是两个对象中放置的内容相同,因此输出true
// s1与s3引用的不是同一个对象,而且两个对象中内容也不同,因此输出false
        System.out.println(s1.equals(s2)); // true
        System.out.println(s1.equals(s3)); // false
    }

在这里插入图片描述

3. int compareTo(String s) 方法

按照字典序进行比较
与equals不同的是,equals返回的是boolean类型,而compareTo返回的是int类型。具体比较方式:

  1. 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值
  2. 如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值
    public static void main(String[] args) {
        String s1 = new String("abc");
        String s2 = new String("ac");
        String s3 = new String("abc");
        String s4 = new String("abcdef");
//大于返回大于0的值,小于返回小于0的值,等于则返回0
        System.out.println(s2.compareTo(s1)); // 不同输出字符差值1
        System.out.println(s1.compareTo(s2)); // 不同输出字符差值-1
        System.out.println(s1.compareTo(s3)); // 相同输出 0
        System.out.println(s1.compareTo(s4)); // 前k个字符完全相同,输出长度差值 -3

    }

在这里插入图片描述

4. int compareToIgnoreCase(String str) 方法(忽略大小写比较)

与compareTo方式相同,但是忽略大小写比较

    public static void main(String[] args) {
        String s1 = new String("hello");
        String s3 = new String("Hello");
        System.out.println(s1.equalsIgnoreCase(s3)); // true

    }

在这里插入图片描述

3.字符串查找( * *

字符串查找也是字符串中非常常见的操作,String类提供的常用查找的方法:

方法功能
char charAt(int index)返回index位置上字符,如果index为负数或者越界,抛出IndexOutOfBoundsException异常
int indexOf(int ch)返回ch第一次出现的位置,没有返回-1
int indexOf(int ch, int fromIndex)从fromIndex位置开始找ch第一次出现的位置,没有返回-1
int indexOf(String str)返回str第一次出现的位置,没有返回-1
int indexOf(String str, int fromIndex)从fromIndex位置开始找str第一次出现的位置,没有返回-1
int lastIndexOf(int ch)从后往前找,返回ch第一次出现的位置,没有返回-1
int lastIndexOf(int ch, int fromIndex)从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返回-1
int lastIndexOf(String str)从后往前找,返回str第一次出现的位置,没有返回-1
int lastIndexOf(String str, int fromIndex)从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返回-1

char charAt(int index)

返回index位置上字符(从0开始),如果index为负数或者越界,抛出IndexOutOfBoundsException异常

    public static void main(String[] args) {
        String s = "hello world";
        System.out.println(s.charAt(1)); // 'e'
        System.out.println(s.charAt(5)); // ' '
        System.out.println(s.charAt(7)); // 'o'
        //System.out.println(s.charAt(12333)); // 编译错误

    }

在这里插入图片描述
在这里插入图片描述

int indexOf(int ch)

返回ch第一次出现的位置,没有返回-1

    public static void main(String[] args) {
        String s = "hello world";
        int index = s.indexOf("w");
        System.out.println(index); // '6'
        int index1 = s.indexOf("l");//默认从头到后一个一个查
        System.out.println(index1);//'2'
        int index2 = s.indexOf("a");
        System.out.println(index2);
    }
}

在这里插入图片描述

int indexOf(int ch, int fromIndex)

从fromIndex位置开始找ch第一次出现的位置,没有返回-1

    public static void main(String[] args) {
        String s = "hello world";
        int index = s.indexOf("w",3);
        System.out.println(index); // '6'
        int index1 = s.indexOf("l",10);
        System.out.println(index1);//'-1'
    }

在这里插入图片描述

int indexOf(String str)

返回str第一次出现的位置,没有返回-1

    public static void main(String[] args) {
        String s = "hello world";
        int index = s.indexOf("wor");
        System.out.println(index); // '6'
        int index1 = s.indexOf("ell");
        System.out.println(index1);//'1'
        int index2 = s.indexOf("apex");
        System.out.println(index2);//'-1'
    }

在这里插入图片描述

int indexOf(String str, int fromIndex)

从fromIndex位置开始找str第一次出现的位置,没有返回-1

    public static void main(String[] args) {
        String s = "hello world";
        int index = s.indexOf("wor",4);
        System.out.println(index); // '6'
        int index1 = s.indexOf("ell",1);
        System.out.println(index1);//'1'
        int index2 = s.indexOf("ld",10);
        System.out.println(index2);//'-1'
    }

在这里插入图片描述

int lastIndexOf(int ch)

从后往前找,返回ch第一次出现的位置,没有返回-1

    public static void main(String[] args) {
        String s = "hello world";
        int index = s.lastIndexOf("w");
        System.out.println(index); // '6'
        int index1 = s.lastIndexOf("e");
        System.out.println(index1);//'1'
        int index2 = s.lastIndexOf("a");
        System.out.println(index2);//'-1'
    }

在这里插入图片描述

int lastIndexOf(int ch, int fromIndex)

从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返回-1

   public static void main(String[] args) {
        String s = "hello world";
        int index = s.lastIndexOf("w",5);
        System.out.println(index); // '-1'
        int index1 = s.lastIndexOf("e",6);
        System.out.println(index1);//'1'
        int index2 = s.lastIndexOf("l",10);
        System.out.println(index2);//'9'
    }

在这里插入图片描述

int lastIndexOf(String str)

从后往前找,返回str第一次出现的位置,没有返回-1

   public static void main(String[] args) {
        String s = "hello world";
        int index = s.lastIndexOf("wor");
        System.out.println(index); // '6'
        int index1 = s.lastIndexOf("ell");
        System.out.println(index1);//'1'
        int index2 = s.lastIndexOf("a");
        System.out.println(index2);//'-1'
    }

在这里插入图片描述

int lastIndexOf(String str, int fromIndex)

从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返回-1

    public static void main(String[] args) {
        String s = "aabbccscwwd";
        int index = s.lastIndexOf("ww",5);
        System.out.println(index); // '-1'
        int index1 = s.lastIndexOf("bb",6);
        System.out.println(index1);//'1'
        int index2 = s.lastIndexOf("wwd",10);
        System.out.println(index2);//'10'
    }

在这里插入图片描述

4.转化

1. 数值和字符串转化

public static void main(String[] args) {


        //数字转字符串
        String s1 = String.valueOf(1234);
        System.out.println(s1);
        String s2 = String.valueOf(12.34);
        System.out.println(s2);
        System.out.println();

        //字符串转数字
        // 注意:Integer、Double等是Java中的包装类型,这个后面会讲到
        int data1 = Integer.parseInt("1234");
        System.out.println(data1);
        double data2 = Double.parseDouble("12.34");
        System.out.println(data2);
        System.out.println();

        //布尔类型和Student类转字符串
        String s3 = String.valueOf(true);
        System.out.println(s3);
        Student student = new Student("Hanmeimei", 18);
        String s4 = String.valueOf(student);
        System.out.println(student);
    }

在这里插入图片描述

大小写转换

    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "HELLO";
// 小写转大写
        //转变为大写,不是在原来的基础上,转变成大写后是一个新的对象。
        System.out.println(s1.toUpperCase());
        System.out.println();
// 大写转小写
        System.out.println(s2.toLowerCase());
    }

在这里插入图片描述

3.字符串转数组

    public static void main(String[] args) {
// 字符串转数组
        String s = "hello";
        char[] ch = s.toCharArray();//toCharArray()返回值是个数组
        for (int i = 0; i < ch.length; i++) {
            System.out.print(ch[i]);
        }
        System.out.println();
// 数组转字符串
        char[] s2 = {'a','b','c','D'};
        String str2 = new String(s2);
        System.out.println(str2);
    }

在这里插入图片描述

4. 格式化

 public static void main(String[] args) {
        String s = String.format("%d-%d-%d", 2019, 9,14);
        System.out.println(s);
    }

在这里插入图片描述

5.字符串替换

使用一个指定的新的字符串替换掉已有的字符串数据,可用的方法如下:

方法功能
String replaceAll(String regex, String replacement)替换所有的指定内容
String replaceFirst(String regex, String replacement))替换收个内容

代码示例: 字符串的替换处理

    public static void main(String[] args) {
        String str = "abcabcaaccbb" ;
        String ret = str.replace("a","__");//不是在原来的基础上替换(把所有的a替换掉)
        System.out.println(ret);                             // 而是产生了新的对象

        String ret1 = str.replaceFirst("ab","__");//只替换了第一个ab
        System.out.println(ret1);

        String ret2 = str.replaceAll("ab","__");//替换所有的ab
        System.out.println(ret2);
    }

在这里插入图片描述

6.字符串拆分

可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。
可用方法如下:

方法功能
String[] split(String regex)将字符串全部拆分
String[] split(String regex, int limit)将字符串以指定的格式,拆分为limit组

代码示例: 实现字符串的拆分处理

 public static void main(String[] args) {
        String str = "hello world hello m" ;
        String[] result = str.split(" ") ; // 按照空格拆分
        for(String s: result) {
            System.out.println(s);
        }
    }

在这里插入图片描述

代码示例: 字符串的部分拆分

    public static void main(String[] args) {
        String str = "hello world hello m" ;
        String[] result = str.split(" ",2) ; // 按照空格拆分成两组
        for(String s: result) {
            System.out.println(s);
        }
    }

在这里插入图片描述
拆分是特别常用的操作. 一定要重点掌握. 另外有些特殊字符作为分割符可能无法正确切分, 需要加上转义.

代码示例: 拆分IP地址

  public static void main(String[] args) {
        String str = "192.168.1.1" ;
        String[] result = str.split("\\.") ;
        for(String s: result) {
            System.out.println(s);
        }
    }

在这里插入图片描述

注意事项:

  1. 字符"|“,”*“,”+"都得加上转义字符,前面加上 " \ \ " .
  2. 而如果是 " \ \ " ,那么就得写成 " \ \ \ \ " .
  3. 如果一个字符串中有多个分隔符,可以用"|"作为连字符

代码示例: 多次拆分

 public static void main(String[] args) {

        String str = "name=zhangsan&age=18" ;
        //方法一:
        String[] result = str.split("&|=") ;
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
        //方法二:
     /*   String[] result = str.split("&") ;
        for (int i = 0; i < result.length; i++) {
            String[] temp = result[i].split("=") ;
            System.out.println(temp[0]+" = "+temp[1]);
        }*/
    }

在这里插入图片描述
这种代码在以后的开发之中会经常出现

7.字符串截取

从一个完整的字符串之中截取出部分内容。可用方法如下:

方法功能
String substring(int beginIndex)从指定索引截取到结尾
String substring(int beginIndex, int endIndex)截取部分内容

代码示例: 观察字符串截取

   public static void main(String[] args) {
        String str = "helloworld" ;
        String ret = str.substring(5);//从下标5之后所有的
        System.out.println(ret);
        System.out.println();

        String ret2 = str.substring(0,6);//[0,6)左闭右开的,所以有四个元素
        System.out.println(ret2);
    }

在这里插入图片描述

注意事项

  1. 索引从0开始
  2. 注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标

8.其他操作方法

font color = “green”>方法功能
String trim()去掉字符串中的左右空格,保留中间空格
String toUpperCase()字符串转大写
String toLowerCase()字符串转小写

代码示例: 观察trim()方法的使用

  public static void main(String[] args) {
        String str = " hello world " ;
        System.out.println("["+str+"]");
        System.out.println("["+str.trim()+"]");
    }

在这里插入图片描述

代码示例: 大小写转换

    public static void main(String[] args) {
        String str = " hello%$$%@#$%world 哈哈哈 " ;
        String upperCase =  str.toUpperCase();
        System.out.println(upperCase);

        String lowerCase = str.toLowerCase();
        System.out.println(lowerCase);
    }

在这里插入图片描述

9. 字符串的不可变性

String是一种不可变对象. 字符串中的内容是不可改变。字符串不可被修改,是因为

  1. String类在设计时就是不可改变的,String类实现描述中已经说明了
    以下来自JDK1.8中String类的部分实现:

在这里插入图片描述
在这里插入图片描述
String类中的字符实际保存在内部维护的value字符数组中,该图还可以看出:

  1. String类被final修饰,表明该类不能被继承
  2. value被修饰被final修饰,表明value自身的值不能改变,即不能引用其它字符数组,但是其引用空间中的内容可以修改。
  1. 所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象
    比如 replace 方法:
    在这里插入图片描述

字符串不可变是因为其内部保存字符的数组被final修饰了,因此不能改变。
这种说法是错误的,不是因为String类自身,或者其内部value被final修饰而不能被修改。
final修饰类表明该类不想被继承,final修饰引用类型表明该引用变量不能引用其他对象,但是其引用对象中的内容是可以修改的。

   public static void main(String[] args) {
        final int array[] = {1,2,3,4,5};
        array[0] = 100;
        System.out.println(Arrays.toString(array));
        array = new int[]{4,5,6}; // 编译报错:Error:(19, 9) java: 无法为最终变量array分配值
    }

在这里插入图片描述

为什么 String 要设计成不可变的?(不可变对象的好处是什么?)

  1. 方便实现字符串对象池. 如果 String 可变, 那么对象池就需要考虑写时拷贝的问题了.
  2. 不可变对象是线程安全的.
  3. 不可变对象更方便缓存 hash code, 作为 key 时可以更高效的保存到 HashMap 中

那如果想要修改字符串中内容,该如何操作呢?

10.字符串修改

注意:尽量避免直接对String类型对象进行修改,因为String类是不能修改的,所有的修改都会创建新对象,效率非常低下

public static void main(String[] args) {
	String s = "hello";
	s += " world";
	System.out.println(s); // 输出:hello world
}

但是这种方式不推荐使用,因为其效率非常低,中间创建了好多临时对象
在这里插入图片描述
StringBuilder和StringBuffer:

public static void main(String[] args) {
            long start = System.currentTimeMillis();
            String s = "";
            for(int i = 0; i < 10000; ++i){
                s += i;
            }
            long end = System.currentTimeMillis();
            System.out.println("String:" + (end - start));


            start = System.currentTimeMillis();
            StringBuffer sbf = new StringBuffer("");
            for(int i = 0; i < 10000; ++i){
                sbf.append(i);
            }
            end = System.currentTimeMillis();
            System.out.println("StringBuffer:" + (end - start));


            start = System.currentTimeMillis();
            StringBuilder sbd = new StringBuilder();
            for(int i = 0; i < 10000; ++i){
                sbd.append(i);
            }
            end = System.currentTimeMillis();
            System.out.println("StringBuilder:" + (end - start));
        }

在这里插入图片描述
从上面运行结果可以看出使用StringBuilder和StringBuffer后效率就会变得很高了。
那么什么是StringBuilder?什么是StringBuffer呢?

三、StringBuilder和StringBuffer

1StringBuilder的介绍

由于String的不可更改特性,为了方便字符串的修改,Java中又提供StringBuilder和StringBuffer类。这两个类大部分功能是相同的,这里介绍 StringBuilder常用的一些方法

font color = “green”>方法功能
StringBuff append(String str)在尾部追加,相当于String的+=,可以追加:boolean、char、char[]、double、float、int、long、Object、String、StringBuff的变量
char charAt(int index)获取index位置的字符
int length()获取字符串的长度
int capacity()获取底层保存字符串空间总的大小
void ensureCapacity(int mininmumCapacity)扩容
void setCharAt(int index,char ch)将index位置的字符设置为ch
int indexOf(String str)返回str第一次出现的位置
int indexOf(String str, int fromIndex)从fromIndex位置开始查找str第一次出现的位置
int lastIndexOf(String str)返回最后一次出现str的位置
int lastIndexOf(String str,int fromIndex))从fromIndex位置开始找str最后一次出现的位置
StringBuff insert(int offset, String str)在offset位置插入:八种基类类型 & String类型 & Object类型数据
StringBuffer deleteCharAt(int index)删除index位置字符
StringBuffer delete(int start, int end)删除[start, end)区间内的字符
StringBuffer replace(int start, int end, String str)将[start, end)位置的字符替换为str
String substring(int start)从start开始一直到末尾的字符以String的方式返回
String substring(int start,int end)将[start, end)范围内的字符以String的方式返回
StringBuffer reverse()反转字符串
String toString()将所有字符按照String的方式返回
    public static void main(String[] args) {
        StringBuilder sb1 = new StringBuilder("hello");
        StringBuilder sb2 = sb1;
// 追加:即尾插-->字符、字符串、整形数字
        sb1.append(' '); // hello
        sb1.append("world"); // hello world
        sb1.append(123); // hello world123

        System.out.println(sb1); // hello world123

        System.out.println(sb1 == sb2); // true

        System.out.println(sb1.charAt(0)); // 获取0号位上的字符 h

        System.out.println(sb1.length()); // 获取字符串的有效长度14

        System.out.println(sb1.capacity()); // 获取底层数组的总大小21

        sb1.setCharAt(0, 'h'); // 设置任意位置的字符 hello world123
        sb1.insert(0, "Hello world!!!"); //在sb10下标的位置插入Hello world!!!
        System.out.println(sb1);// Hello world!!!hello world123

        System.out.println(sb1.indexOf("Hello")); // 获取Hello第一次出现的位置0
        System.out.println(sb1.lastIndexOf("hello")); // 获取hello最后一次出现的位置14

        sb1.deleteCharAt(0); // 删除首字符----》ello world123
        sb1.delete(0,5); // 删除[0, 5)范围内的字符 -----》  world123
        String str = sb1.substring(0, 5); // 截取[0, 5)区间中的字符以String的方式返回---》world
        System.out.println(str);//world

        sb1.reverse(); // 字符串逆转
        str = sb1.toString(); // 将StringBuffer以String的方式返回
        System.out.println(str);
    }

在这里插入图片描述

从上述例子可以看出:String和StringBuilder最大的区别在于String的内容无法修改,而StringBuilder的内容可以修改。频繁修改字符串的情况考虑使用StringBuilder。
注意:String和StringBuilder类不能直接转换。如果要想互相转换,可以采用如下原则:
String变为StringBuilder: 利用StringBuilder的构造方法或append()方法
StringBuilder变为String: 调用toString()方法

2. String、StringBuffer、StringBuilder的区别( * * *

  1. String的内容不可修改,StringBuffer与StringBuilder的内容可以修改.
  2. StringBuffer与StringBuilder大部分功能是相似的
  3. StringBuffer采用同步处理,属于线程安全操作;而StringBuilder未采用同步处理,属于线程不安全操作

四、 String类练习题

1.字符串中的第一个唯一字符

给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

示例 1:

输入: s = “leetcode”
输出: 0
示例 2:

输入: s = “loveleetcode”
输出: 2
示例 3:

输入: s = “aabb”
输出: -1

提示:

1 <= s.length <= 105
s 只包含小写字母

思路

  1. 申请一个计数数组
  2. 遍历字符串的每一个字符,把字符出现的次数存储在数组类名
  3. 再次遍历字符串的每个字符,如果在数组里面是1那么就返回当前的数组下标

代码

class Solution {
        public int firstUniqChar(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {// 统计每个字符出现的次数
            char ch = s.charAt(i);
            count[ch - 97]++;
        }
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if(count[ch -97] == 1){
                return i;
            }
        }
        return -1;
    }
}

2.字符串最后一个单词的长度

描述
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
输入描述:
输入一行,代表要计算的字符串,非空,长度小于5000。

输出描述:
输出一个整数,表示输入字符串最后一个单词的长度。

示例1
输入:
hello nowcoder

输出:
8

说明:
最后一个单词为nowcoder,长度为8

思路

  1. 利用lastIndexOf找到最后一个空格的下标
  2. 利用String substring来截取最后一个空格之后的内容

代码:

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
           String s = in.nextLine();
           int index = s.lastIndexOf(' ') ;
           String str = s.substring(index+1);
           System.out.println(str.length());
        }
    }
}

3. 验证回文串

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。

字母和数字都属于字母数字字符。

给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。

示例 1:

输入: s = “A man, a plan, a canal: Panama”
输出:true
解释:“amanaplanacanalpanama” 是回文串。
示例 2:

输入:s = “race a car”
输出:false
解释:“raceacar” 不是回文串。
示例 3:

输入:s = " "
输出:true
解释:在移除非字母数字字符之后,s 是一个空字符串 “” 。
由于空字符串正着反着读都一样,所以是回文串。

提示:

1 <= s.length <= 2 * 105
s 仅由可打印的 ASCII 字符组成

代码:

 class Solution {
        public  boolean idNumOrCharacter(char ch){
            if (ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z'){
                return true;
            }
            return false;
        }
        public  boolean isPalindrome(String s) {
            s = s.toLowerCase();
            //1.定义i,j,ch(每一步接收的字符)
            int i = 0;
            int j = s.length() - 1;
            //2.如果i!=j
            while (i < j){
            //3.i一直走到一个合法的字符
                while (i < j && !idNumOrCharacter(s.charAt(i))){
                    i++;
                }
                //4.j一直走到一个合法的字符
                while (i < j && !idNumOrCharacter(s.charAt(j))){
                    j--;
                }if (s.charAt(i) == s.charAt(j)){//5.对应下标一样
                    i++;
                    j--;
                }else {//6.对应下标不一样 return false
                    return false;
                }
            }
            return true;//i和j相遇,说明是回文数
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值