Java String indexOf()方法和java.lang.StringBuilder.setLength()方法实例

描述:

这个方法有如下不一样的变体:java

  • public int indexOf(int ch): 返回此字符串指定字符第一次出现,或若是该字符不出现-1处的索引。yii

  • public int indexOf(int ch, int fromIndex): 返回索引这个字符串中指定字符第一次出现处,开始搜索指定的索引处或-1,若是该字符不会出现。ui

  • int indexOf(String str): 返回此字符串指定子字符串的第一次出现处的索引。若是不出现做为一个子串,则返回-1.spa

  • int indexOf(String str, int fromIndex): 返回索引这个字符串中指定子字符串的第一次出现处,从指定的索引处。若是它不出现,则返回-1.索引

语法

此方法定义的语法以下:字符串

public int indexOf(int ch )
or
public int indexOf(int ch, int fromIndex)
or
int indexOf(String str)
or
int indexOf(String str, int fromIndex)

参数

这里是参数的细节:string

  • ch -- 一个字符.io

  • fromIndex -- 从这个索引开始搜索.编译

  • str -- 一个字符串.class

返回值:

  • 看描述说明

例子:

import java.io.*;

public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      String SubStr1 = new String("Tutorials");
      String SubStr2 = new String("Sutorials");

      System.out.print("Found Index :" );
      System.out.println(Str.indexOf( 'o' ));
      System.out.print("Found Index :" );
      System.out.println(Str.indexOf( 'o', 5 ));
      System.out.print("Found Index :" );
      System.out.println( Str.indexOf( SubStr1 ));
      System.out.print("Found Index :" );
      System.out.println( Str.indexOf( SubStr1, 15 ));
      System.out.print("Found Index :" );
      System.out.println(Str.indexOf( SubStr2 ));
   }
}

这将产生如下结果:

Found Index :4
Found Index :9
Found Index :11
Found Index :-1
Found Index :-1

 

 

java.lang.StringBuilder.setLength() 方法将字符序列的长度。该序列被改变为其长度由参数指定一个新的字符序列。
若是newLength参数大于或等于当前的长度,足以让空字符('u0000“)附加以使长度成为newLength参数。

声明

如下是java.lang.StringBuilder.setLength()方法的声明

public void setLength(int newLength)

参数

  • newLength -- 这是新的长度。

返回值

此方法不返回任何值。

异常

  • IndexOutOfBoundsException -- 若是newLength参数为负。

例子

下面的例子显示java.lang.StringBuilder.setLength()方法的使用。

package com.yiibai;

import java.lang.*;

public class StringBuilderDemo {

  public static void main(String[] args) {
  
    StringBuilder str = new StringBuilder("tutorials");
    System.out.println("string = " + str);  
    // length of StringBuilder
    System.out.println("length = " + str.length());
        
    // set the length of StringBuilder to 5
    str.setLength(5);
        
    // print new StringBuilder value after changing length
    System.out.println("After set, string = " + str);
    // length of StringBuilder after changing length
    System.out.println("length = " + str.length());
  }
}

让咱们来编译和运行上面的程序,这将产生如下结果:

string = tutorials
length = 9
After set, string = tutor
length = 5
相关文章
相关标签/搜索