codecamp

Java 字符串字符

Java数据类型教程 - Java字符串字符


索引字符

您可以使用charAt()方法从String对象中获取特定索引处的字符。索引从零开始。

下面的代码打印索引值和字符在“W3CSCHOOL.CN"字符串中的每个索引处:

public class Main {
  public static void main(String[] args) {
    String str = "W3CSCHOOL.CN";

    // Get the length of string
    int len = str.length();

    // Loop through all characters and print their indexes
    for (int i = 0; i < len; i++) {
      System.out.println(str.charAt(i) + "  has  index   " + i);
    }

  }
}

上面的代码生成以下结果。

Snipaste_2024-01-08_15-01-10

测试字符串是否为空

测试String对象是否为空。空字符串的长度为零。

有三种方法可以检查空字符串:

  • isEmpty()方法。
  • equals()方法。
  • 获取字符串的长度,并检查它是否为零。

以下代码显示如何使用三种方法:

public class Main {
  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "";

    // Using the isEmpty() method
    boolean empty1 = str1.isEmpty(); // Assigns false to empty1
    boolean empty2 = str2.isEmpty(); // Assigns true to empty1

    // Using the equals() method
    boolean empty3 = "".equals(str1); // Assigns false to empty3
    boolean empty4 = "".equals(str2); // Assigns true to empty4

    // Comparing length of the string with 0
    boolean empty5 = str1.length() == 0; // Assigns false to empty5
    boolean empty6 = str2.length() == 0; // Assigns true to empty6

  }
}

更改案例

要将字符串的内容转换为小写和大写,请分别使用toLowerCase()和toUpperCase()方法。

String str1 = new String("Hello"); // str1  contains "Hello" 
String str2 = str1.toUpperCase();   // str2 contains "HELLO" 
String str3 = str1.toLowerCase();   // str3 contains "hello"


Java 字符串比较
Java 字符串搜索
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Java 数据类型介绍

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }