stringindexmethods.java
来自「《Java面向对象程序设计》例子源代码.轻松学习书本.」· Java 代码 · 共 36 行
JAVA
36 行
//StringIndexMethods.java
import javax.swing.*;
public class StringIndexMethods {
public static void main( String args[] ){
String letters = "abcdefghabcdefgh";
//调用String类的indexOf方法定位某个字符在字符串中第一次出现的位置
String output = "'c' is located at index " + letters.indexOf( 'c' );
output += "\n'a' is located at index " + letters.indexOf( 'a', 1 );
output += "\n'$' is located at index " + letters.indexOf( '$' );
//调用lastIndexOf方法定位某个字符在字符串中最后一次出现的位置
output += "\nLast 'c' is located at index " +
letters.lastIndexOf( 'c' );
output += "\nLast 'a' is located at index " +
letters.lastIndexOf( 'a', 10 );
output += "\nLast '$' is located at index " +
letters.lastIndexOf( '$' );
//调用indexOf方法定位某个子字符串在字符串中第一次出现的位置
output += "\n\"def\" is located at index " +
letters.indexOf( "def" );
output += "\n\"def\" is located at index " +
letters.indexOf( "def", 7 );
output += "\n\"hello\" is located at index " +
letters.indexOf( "hello" );
//调用lastIndexOf方法定位某个子字符在字符串中最后一次出现的位置
output += "\nLast \"def\" is located at index " +
letters.lastIndexOf( "def" );
output += "\nLast \"def\" is located at index " +
letters.lastIndexOf( "def", 25 );
output += "\nLast \"hello\" is located at index " +
letters.lastIndexOf( "hello" );
JOptionPane.showMessageDialog( null, output,
"字符串检索", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?