学习笔记16(一些String类的方法)

学习笔记16(一些String类的方法),第1张

学习笔记16(一些String类的方法) 1、搜索字符串的方法

String类提供了几种在字符串中搜索字符串的方法。子字符串通常用于指代属于一个字符串的一部分的字符串。

 下面看例子:

String str = "Four score and seven years ago";
if (str.startsWith("Four"))
 System.out.println("The string starts with Four.");
else
 System.out.println("The string does not start with Four.");

显然这里返回true,但是如果改为str.startsWith("four")就会返回false。

String str = "Four score and seven years ago";
String str2 = "Those seven years passed quickly";
if (str.regionMatches(15, str2, 6, 11))
 System.out.println("The regions match.");
else
 System.out.println("The regions do not match.");

此代码将显示“The regions match.”。str串的指定区域从15开始,而str2串的指定区域从6开始。这两个区域都由11个字符组成。str字符串中的指定区域是“seven years”,而str2字符串中的指定区域也是“seven years”。因为这两个区域匹配,所以此代码中的区域匹配方法返回true。

2、查询位置的方法

 例子:

String str = "Four score and seven years ago";
int first, last;
first = str.indexOf('r');
last = str.lastIndexOf('r');
System.out.println("The letter r first appears at " +
 "position " + first);
System.out.println("The letter r last appears at " +
 "position " + last);
The letter r first appears at position 3 The letter r last appears at position 24

 如果我们希望找到一个字符串中所有的所有的r,可以使用循环,注意在每次循环的时候要将起始检查字符串的位置改为上一个出现这个字符的位置加1:

String str = "Four score and seven years ago";
int position;
System.out.println("The letter r appears at the " +
 "following locations:");
position = str.indexOf('r');
while (position != −1)
{
 System.out.println(position);
 position = str.indexOf('r', position + 1);
}
The letter r appears at the following locations: 3 8 24

lastIndexOf可以倒序输出,注意看这里更新开始的检查位置的 *** 作和上面的不一样:

String str = "Four score and seven years ago";
int position;
System.out.println("The letter r appears at the " +
 "following locations.");
position = str.lastIndexOf('r');
while (position != −1)
{
 System.out.println(position);
 position = str.lastIndexOf('r', position − 1);
}
The letter r appears at the following locations. 24 8 3

当我们希望找到子串时:

String str = "and a one and a two and a three";
int position;
System.out.println("The word and appears at the " +
 "following locations.");
position = str.indexOf("and");
while (position != -1)
{
 System.out.println(position);
 position = str.indexOf("and", position + 1);
}
The word and appears at the following locations. 0 10 20
 3、截取字符串以及将字符串转换为char数组的方法

 例子:

String fullName = "Cynthia Susan Lee";
String lastName = fullName.substring(14);
System.out.println("The full name is " + fullName);
System.out.println("The last name is " + lastName);
The full name is Cynthia Susan Lee The last name is Lee

注意subString方法返回的是一个新的string类对象。 

 将字符串转换为数组的例子:

String fullName = "Cynthia Susan Lee";
char[] nameArray = new char[5];
fullName.getChars(8, 13, nameArray, 0);
System.out.println("The full name is " + fullName);
System.out.println("The values in the array are:");
for (int i = 0; i < nameArray.length; i++)
 System.out.print(nameArray[i] + " ");
The full name is Cynthia Susan Lee The values in the array are: S u s a n

有时候我们需要检查用户的输入,对每一位上的字符有要求,这时候我们就可以将字符串转换为单个字符再进行检查:

import java.util.Scanner;



public class StringAnalyzer
{
    public static void main(String [] args)
    {
        String input; // To hold input
        char[] array; // Array for input
        int letters = 0; // Number of letters
        int digits = 0; // Number of digits
        int whitespaces = 0; // Number of whitespaces

        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);

        // prompt the user to enter a line of input.
        System.out.print("Enter a string: ");
        input = keyboard.nextLine();

        // Convert the string to a char array.
        array = input.toCharArray();

        // Analyze the characters.
        for (int i = 0; i < array.length; i++)
        {
            if (Character.isLetter(array[i]))
                letters++;
            else if (Character.isDigit(array[i]))
                digits++;
            else if (Character.isWhitespace(array[i]))
                whitespaces++;
        }

        // Display the results.
        System.out.println("That string contains " +
                letters + " letters, " +
                digits + " digits, and " +
                whitespaces +
                " whitespace characters.");
    }
}
Enter a string: 99 red balloons [Enter] That string contains 11 letters, 2 digits, and 2 whitespace characters.
4、修改原字符串的方法

 其中contact方法和+的作用一样:

fullName = firstName + lastName;
fullName = firstName.concat(lastName);

而对于replace方法,就是将原来字符串中所有的A字符换成B字符,注意,这个方法是先复制原来的字符串,再更改,也就是说这个方法不修改原来的字符串:

String str1 = "Tom Talbert Tried Trains";
String str2;
str2 = str1.replace('T', 'D');
System.out.println(str1);
System.out.println(str2);
Tom Talbert Tried Trains Dom Dalbert Dried Drains

 trim方法:

String greeting1 = " Hello ";
String greeting2;
greeting2 = greeting1.trim();
System.out.println("*" + greeting1 + "*");
System.out.println("*" + greeting2 + "*");
* Hello * *Hello*
 5、valueOf方法

String还提供了拥有好几个重载方法的valueOf方法。此方法接受任何原始数据类型的值作为其参数,并返回该值的String形式。

boolean b = true;
char [] letters = { 'a', 'b', 'c', 'd', 'e' }; 
double d = 2.4981567;
int i = 7;
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(letters));
System.out.println(String.valueOf(letters, 1, 3));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(i));

true abcde bcd 2.4981567 7

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5712939.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存