LoginSignup
0
1

Java|Stringクラスのメソッドの使い方(Ⅰ)

Posted at

はじめに

JavaのStringクラスには文字列を扱うためのメソッドが入っています。今回はそのメソッドについて紹介しようと思います。

文字列を扱うメソッド

replace()

  • 書き方:str.replace(char searchChar, char newChar)
  • 戻り値:String

 replaceメソッドは、文字列を別の文字または文字列に置き換えるために使われます。最初の引数に置き換え元の文字を指定し、2番目の引数に置き換える文字を指定します。

public class Main{
	public static void main(String[] args){
		String myStr = "aaaa";
		System.out.println(myStr.replace("aa", "b")); // bb
	}
}

charAt()

  • 書き方:str.charAt(int index)
  • 戻り値:char

 charAtメソッドは、文字列から引数で指定された位置(index)にある文字を抽出して返します。引数に指定する値は、抽出する位置(index)の値で0から始まります。もし5番目の文字を抽出したい場合は、引数に「4」を指定します。

 文字列範囲外の引数を指定すると、java.lang.StringIndexOutOfBoundsException例外が発生します。

public class Main{
	public static void main(String[] args){
		String myStr = "abcde";
		System.out.println(myStr.charAt(4)); // e
	}
}

indexOf()

  • 書き方:str.indexOf(String str)
  • 戻り値:int

 indexOfメソッドは、引数に指定された文字または文字列の位置(index)を返します。引数に指定する値は、文字または文字列で0から始まります。抽出しようとする値が存在しない場合は「-1」を返します。

public class Main{
	public static void main(String[] args){
		String myStr = "Hello, world!";
		
		String myFirValue = "world";
		String mySndValue = "word";
        
		int indexOfFirValue = myStr.indexOf(myFirValue);
		int indexOfSndValue = myStr.indexOf(mySndValue);
		
		System.out.println("Index of " + myFirValue +": " + indexOfFirValue); // Index of world: 7
		System.out.println("Index of " + mySndValue +": " + indexOfSndValue); // Index of word: -1
	}
}

substring()

  • 書き方:str.substring(int startIndex) または str.substring(int startIndex, int endIndex)
  • 戻り値:String

 subStringメソッドは文字列を部分切り取り、必要な部分の文字列を返します。最初の引数に抽出しようとする文字列の開始位置(index)を指定し、0から始まります。2番目の引数は任意値で、抽出しようとする文字列の最後の位置(index)を指定します。その位置の文字は返されません。

public class Main{
	public static void main(String[] args){
		String myStr = "Hello, world!";
		
		String myFirValue = myStr.substring(3);
		String mySndValue = myStr.substring(7, 12);
		
		System.out.println(myFirValue); // "lo, world"
		System.out.println(mySndValue); // "world"
	}
}

startsWith() / endsWith()

  • 書き方:str.startsWith(String chars) / str.endsWith(String chars)
  • 戻り値:boolean

 startsWithメソッドは、提示された文字列が引数に指定した文字で始まるかどうかをチェックします。一方、endsWithメソッドは、提示された文字列が引数に指定した文字で終わるかどうかをチェックします。

public class Main{
	public static void main(String[] args){
		String myStr = "Happy Birthday";
		
		System.out.println(myStr.startsWith("Hap"));   // true
		System.out.println(myStr.startsWith("app"));   // false
		
		System.out.println(myStr.endsWith("day"));     // true
		System.out.println(myStr.endsWith("t"));       // false 
	}
}

まとめ

  • replace() - 文字列置換
  • charAt() - 指定した位置の文字抽出
  • indexOf() - 指定した文字の位置(index)抽出
  • substring() - 必要な部分の文字列抽出
  • startsWith() / endsWith() - 指定文字で始まるか/終わるか判断
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1