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" ";
output += " ";
// 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 ";
output += " ";
// Test method endsWith
for ( int i = 0; i < strings.length; i++ )
if ( strings[ i ].endsWith( "ed" ) )//判断这个字符串是不是以ed结尾
output += """ + strings[ i ] +
"" ends with "ed" ";
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 += " 'a' is located at index " +
letters.indexOf( 'a', 1 ); //第2个参数是开始查找的起始下标
output += " '$' is located at index " +
letters.indexOf( '$' );//$的起始下标
// test lastIndexOf to find a character in a string
output += " Last 'c' is located at index " +
letters.lastIndexOf( 'c' );//下一个c的下标
output += " Last 'a' is located at index " +
letters.lastIndexOf( 'a', 25 );//第26个参数是开始查找的起始下标
output += " Last '$' is located at index " +
letters.lastIndexOf( '$' );
// test indexOf to locate a substring in a string
output += " "def" is located at index " +
letters.indexOf( "def" );//def的下标i=3
output += " "def" is located at index " +
letters.indexOf( "def", 7 );//第8个参数是开始查找的起始下标
output += " "hello" is located at index " +
letters.indexOf( "hello" );
// test lastIndexOf to find a substring in a string
output += " Last "def" is located at index " +
letters.lastIndexOf( "def" );
output += " Last "def" is located at index " +
letters.lastIndexOf( "def", 25 );
output += " Last "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结尾