字符串查找
1、StringStartEnd.java示例
查询字串是否以某字串开头和结尾:startsWith和endWith方法
源代码:
// StringStartEnd.java
// This program demonstrates the methods startsWith and
// endsWith of the String class.
import javax.swing.*;
public class StringStartEnd {
public static void main( String args[] )
{
String strings[] = { "started", "starting",
"ended", "ending" };
String output = "";//输出字符串
// Test method startsWith
for ( int i = 0; i < strings.length; i++ )
if ( strings[ i ].startsWith( "st" ) )//判断这个字符串是不是以st开始
output += "\"" + strings[ i ] +
"\" starts with \"st\"\n";
output += "\n";
// Test method startsWith starting from position
// 2 of the string
for ( int i = 0; i < strings.length; i++ )
if ( strings[ i ].startsWith( "art", 2 ) ) //判断art是不是从第二个位置开始
output +=
"\"" + strings[ i ] +
"\" starts with \"art\" at position 2\n";
output += "\n";
// Test method endsWith
for ( int i = 0; i < strings.length; i++ )
if ( strings[ i ].endsWith( "ed" ) )//判断这个字符串是不是以ed结尾
output += "\"" + strings[ i ] +
"\" ends with \"ed\"\n";
JOptionPane.showMessageDialog( null, output,
"Demonstrating String Class Comparisons",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
1、StringIndexMethods.java
在字串查找字符或子串,调用indexOf和lastIndexOf方法即可
源代码:
// This program demonstrates the String
// class index methods.
import javax.swing.*;
public class StringIndexMethods {
public static void main( String args[] )
{
String letters = "abcdefghijklmabcdefghijklm";
String output;
// test indexOf to locate a character in a string
output = "'c' is located at index " +
letters.indexOf( 'c' );//c的起始下标
output += "\n'a' is located at index " +
letters.indexOf( 'a', 1 ); //第2个参数是开始查找的起始下标
output += "\n'$' is located at index " +
letters.indexOf( '$' );//$的起始下标
// test lastIndexOf to find a character in a string
output += "\n\nLast 'c' is located at index " +
letters.lastIndexOf( 'c' );//下一个c的下标
output += "\nLast 'a' is located at index " +
letters.lastIndexOf( 'a', 25 );//第26个参数是开始查找的起始下标
output += "\nLast '$' is located at index " +
letters.lastIndexOf( '$' );
// test indexOf to locate a substring in a string
output += "\n\n\"def\" is located at index " +
letters.indexOf( "def" );//def的下标i=3
output += "\n\"def\" is located at index " +
letters.indexOf( "def", 7 );//第8个参数是开始查找的起始下标
output += "\n\"hello\" is located at index " +
letters.indexOf( "hello" );
// test lastIndexOf to find a substring in a string
output += "\n\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,
"Demonstrating String Class \"index\" Methods",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
- if(a.startsWith(b))
- //判断字符串a 是不是以字符串b开头.
- if(a.endsWith(b))
- //判断字符串a 是不是以字符串b结尾