开始使用免费开始使用

String 有多长?

文本有各种长度——从单个字符到整段段落。了解一个 String 包含多少字符,对校验、格式化和处理文本都很重要。让我们来看看 Java 如何帮助您测量字符串长度!

本练习是课程的一部分

Java 入门

查看课程

练习说明

  • 使用 .length() 方法获取变量 bookName 的长度,并将结果保存为 bookNameLength
  • 求作者姓名 "Terry Pratchett" 的长度,并使用正确的基本数据类型保存结果。

交互式实操练习

通过完成这段示例代码来试试这个练习。

class HowLong {
    public static void main(String[] args) {
    
        String bookName = "Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch";
        
        // Find the length of bookName
        int bookNameLength = bookName.____();
        
        // Find the length of the String and save it
        ____ authorNameLength = "Terry Pratchett".____;
        
        System.out.println("The length of the book title is " + bookNameLength);
        System.out.println("The length of the author's name is " + authorNameLength);
    }
}
编辑并运行代码