Using substring( ) in Java

By: Fazal Emailed: 1610 times Printed: 2079 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

You can extract a substring using substring( ). It has two forms. The first is String substring(int startIndex)

Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string.

The second form of substring( ) allows you to specify both the beginning and ending index of the substring:

String substring(int startIndex, int endIndex)

Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index. The following program uses substring( ) to replace all instances of one substring with another within a string:

// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { // replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}

The output from this program is shown here:

This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(14)


1. View Comment

Where is the methods related

View Tutorial          By: Osvaldo F. L. Mendes at 2008-03-17 15:40:48
2. View Comment

The example program by itself doesn't solve any purpose. However it shows how to use the substring funtion to extract a portion of the string.

View Tutorial          By: Fazal at 2008-03-17 21:23:10
3. View Comment

I need to know the parameters that we need to pass on substring() methods.

View Tutorial          By: puru at 2008-09-08 00:33:46
4. View Comment

Hi puru, The syntax is substring(int startIndex, int endIndex). Therefore you should pass two integer numbers to this method. The first one indicates the starting index and the second one indicates the ending index. For example, if you want to take the substring 'He' from the String 'Hello' then you would specify substring(0,2) which means start from the first character and finish after the second character.

View Tutorial          By: Fazal at 2008-09-12 20:17:53
5. View Comment

voire pluse a des command java

View Tutorial          By: lahcine moubarek at 2009-02-16 01:59:17
6. View Comment

Could you somehow use the substring method to parse text? For example, I have the string:
"Name: Will Smith School: West Project: Earth Day Name: Mary Joe School: Central Project: Volcano"

I would like to parse the text by topics so it appears as such:
"Name: Will Smith
School: West
Project: Earth Day
Name: Mary Joe
School: Central
Project: Volcano"


View Tutorial          By: Eric at 2009-04-26 19:20:26
7. View Comment

@Eric

You would have to know the locations of where you would like to parse before using a method like this.

A better approach would be use regular expressions and a scanner. You can Google how to use that type of functionality.

(I know this is over a year later in replying, but someone else might want to know the same thing)


View Tutorial          By: Guy at 2010-09-27 17:18:31
8. View Comment

I think the programmer overlooked that "this" has "is" within it. So, if I'm correct, the expected final result was "This was a test. This was, too." =P

View Tutorial          By: Joe Schmoe at 2010-10-16 00:01:27
9. View Comment

thanks for this sample.. it possible to handle the error of indexOf if it could not find the string? how?

View Tutorial          By: nel at 2011-06-13 22:59:45
10. View Comment

can you help me in codings for get an output like this:
If user input is abc, the substring has to be shown like
abc
ab
a
ab
a
a

help please..


View Tutorial          By: Sudhar at 2011-08-24 05:47:53
11. View Comment

Hey guys, can u help me out over here..
this is a game called wheel of fortune..
nd waht i need to do is replace dashes with the letter for example ..
if the word is fr example "APPLE" ..
nd the user enters "P" .. then the dash at the position where P should be should get replaced by the letter..so sumting like this "_ PP_ _

but i cant seem to get it to work ..nd i need to do this wid substring and charAt..plzzzz HELP ME !:(

HERE'S MY CODE ...PLZ HELP ASAP ..THNKS :)

/*
* Ridge Fernandes
* WheelOfFortuneCulminating.java
* The game wheel of Fortune which is a two player game.The players enter letters, or vowels and try their best to solve the puzzle so they can win the game.
* ICS 3U1
* December.29,2011
*/
/*START
*Display "/////////////////////////////////////
*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
* WW WW HH HH EEEEEE EEEEEE LL
* WW WW HH HH EE EE LL
* WW WW WW HHHHHHH EEEEEE EEEEEE LL
* WW WW WW HH HH EE EE LL
* WW WW HH HH EEEEEE EEEEEE LLLLLL
*
* OOOOOO FFFFFF
* OO OO FF
* OO OO FFFFFF
* OO OO FF
* OOOOOO FF
*
* FFFFFF OOOOOO RRRRRR TTTTTT UU UU NNNN NN EEEEEE
* FF OO OO RR RR TT UU UU NN NN NN EE
* FFFFFF OO OO RRRRRR TT UU UU NN NN NN EEEEEE
* FF OO OO RR RR TT UU UU NN NN NN EE
* FF OOOOOO RR RR TT UUUUUU NN NNNNN EEEEEE
*Display "/////////////////////////////////////
*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
*
*player <-- " "
*player1
*player2
*playerSpin1 <-- 0
*playerSpin2 <-- 0
*player1money1 <-- 0
*player2money2 <-- 0
*money <-- 0
*selection
*choice
*word
*
*Display "Enter the first player's name "
*get player1
*Display "Enter the second player's name "
*get player2
*selection <= (2 x Math.random() plus 1) // a switch statement is used here, this selects the player that gets to play first by randomizing the selection
*case 1: Display "The player ", player1, " gets to play first "
*case 2: Display "The player ", player2, " gets to play first "
*
*Display ("1) Play the game: ")
*Display ("2) Instructions of wheel of fortune: ")
*Display ("3) Quit: ")
*get choice
*
*if (choice becomes 1)
*Display ("You have started the game wheel of fortune")
*spin <-- (13 x Math.random() plus 1) // this is used to spin the wheel of fortune by randomizing each time it is spun
*
*case 1: Display ("You have landed on Lose a turn"),money <-- -15
case 2: Display ("You have landed on $300"),money<-- 300
case 3: Display("You have landed on $400"),money<-- 400
case 4: Display("You have landed on $800"),money<-- 800
case 5: Display("You have landed on $1000"),money<-- 1000
case 6: Display("You have landed on $1500"),money<-- 1500
case 7: Display("You have landed on $2000"),money<-- 2000
case 8: Display("You have landed on BANKRUPTCY"),money<-- -5
case 9: Display("You have landed on $3000"),money<-- 3000
case 10: Display("You have landed on $3500"),money<-- 3500
case 11: Display("You have landed on $4000"),money<-- 4000
case 12: Display("You have landed on $4500"),money<-- 4500
case 13: Display("You have landed on BONUS: $5000"),money<-- 5000
*
*if (player.equals(player1))
* {
*/


import java.util.Scanner;
public class WheelOfFortuneCulminating{
public static void main(String[] args){
Scanner in = new Scanner(System.in);

System.out.print("//////////////////////////////////////");
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ");
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ");
System.out.println(" WW WW HH HH EEEEEEE EEEEEEE LL ");
System.out.println(" WW WW HH HH EE EE LL ");
System.out.println(" WW WW WW HHHHHHHH EEEEEEE EEEEEEE LL ");
System.out.println(" WW WW WW HH HH EE EE LL ");
System.out.println(" WWW WWW HH HH EEEEEEE EEEEEEE LLLLLLL ");
System.out.println();
System.out.println(" OOOOOOO FFFFFFF ");
System.out.println(" OO OO FF ");
System.out.println(" OO OO FFFFFFF ");
System.out.println(" OO OO FF ");
System.out.println(" OOOOOOO FF ");
System.out.println();
System.out.println(" FFFFFFF OOOOOOO RRRRRRR TTTTTTTT UU UU NNN NN EEEEEEE ");
System.out.println(" FF OO OO RR RR TT UU UU NN NN NN EE ");
System.out.println(" FFFFFFF OO OO RRRRRRR TT UU UU NN NN NN EEEEEEE ");
System.out.println(" FF OO OO RR RR TT UU UU NN NN NN EE ");
System.out.println(" FF OOOOOOO RR RR TT UUUUUUU NN NNNN EEEEEEE ");
System.out.println("/////////////////////////////////////");
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ");
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\n" );


String player1;
String answer = "";
String letter = " ";
String dash = " _ ";
String ansOut = " _ ";
String vowels;
int player = 0;
int mainFunctions;
int playerSpin1 = 0;
int player1money1 = 0;
int money = 0;
int selection;
int choice;
int choice2 = 0;



System.out.println("Enter the first player's name");
player1 = in.nextLine();

System.out.println("The first player " + player1 + " gets to play first");


System.out.println();
System.out.println("1. Play the game:");
System.out.println("2. Instructions of wheel of fortune:");
System.out.println("3. Quit:");
choice = in.nextInt();
System.out.println();

if (choice == 1)
{
System.out.println("You have started the game wheel of fortune: ");//

int spin;
spin = (int) (13* Math.random() + 1);

switch(spin)
{

//case 1: System.out.println("You have landed on Lose a turn");money = -15;break;
case 2: System.out.println("You have landed on $300");money = 300;break;
case 3: System.out.println("You have landed on $400");money = 400;break;
case 4: System.out.println("You have landed on $800");money = 800;break;
case 5: System.out.println("You have landed on $1000");money = 1000;break;
case 6: System.out.println("You have landed on $1500");money = 1500;break;
case 7: System.out.println("You have landed on $2000");money = 2000;break;
case 8: System.out.println("You have landed on BANKRUPTCY");money = -1;break;
case 9: System.out.println("You have landed on $3000");money = 3000;break;
case 10: System.out.println("You have landed on $3500");money = 3500;break;
case 11: System.out.println("You have landed on $4000");money = 4000;break;
case 12: System.out.println("You have landed on $4500");money = 4500;break;
case 13: System.out.println("You have landed on BONUS: $5000");money = 5000;break;
// return (spin)
}

if (money != -1)
{
player1money1 += money;
}
else if (money == -1)
{

//player1money1 = 0;
}

}

System.out.println ("\n" + player1 + " = " + "$" + money );

int randomWord;
randomWord = (int) (5 * Math.random() + 1);

if (randomWord == 1)
{
answer = "APPLE"; ansOut = " _ _ _ _ _ ";
}
else if (randomWord == 2)
{
answer = "PSYCHOLOGY"; ansOut = " _ _ _ _ _ _ _ _ _ _ ";
}
else if (randomWord == 3)
{
answer = "BIRD"; ansOut = " _ _ _ _ ";
}
else if (randomWord == 4)
{
answer = "SURGEON"; ansOut = " _ _ _ _ _ _ _ ";
}
else if (randomWord == 5)
{
answer = "PIGEON"; ansOut = " _ _ _ _ _ _ ";
}


System.out.println("\nThe secret word to guess is: ");

for (int i = 0; i < answer.length(); i++)
{
if (letter.charAt(0) == answer.charAt(i))
{
ansOut = ansOut.substring(0,i) + letter.charAt(i) + ansOut.substring(i);
}
}System.out.print(ansOut);



System.out.println("\n \n What would you like to do ?");
System.out.println("1) Enter a letter: ");
System.out.println("2) Purchase a vowel($250): ");
System.out.println("3) Solve the puzzle ");
choice2 = in.nextInt();

if (choice2 == 1)
{
System.out.println("Enter your letter: ");
letter = in.nextLine();
letter = in.nextLine();

for (int i = 0; i < answer.length(); i++)
{
if ( letter.charAt(i) == answer.charAt(0))
{
ansOut = letter.substring(0,i) + letter.charAt(i) + ansOut.substring(i);
}
}
System.out.print(ansOut);

}












else if ( choice == 2)
{

System.out.println("The instructions is as follows: ");
System.out.println("1) This is a two player game and is also based on a hangman kind of a game. This game starts when the players enter their name and begin to start the game. The game continues until the puzzle is solved by any one of the contestants. And the game continues until the person with the highest cash value wins. At the end, the announced winner gets to go into the bonus round where he/she can be able to win a car or a prize from $10,000 to $20,000");
System.out.println();
System.out.println("2) The current player should enter the letter. Once the word is correct, the player gets 1000 dollars to the players account");
System.out.println();
System.out.println("3) Once this is done, the player is asked to spin the wheel and depending on that it might end up on Bankruptcy or a dollar value which can range from $100 to $5000.If they get a letter that appears 3 times in the puzzle for example, then the value on the wheel is multiplied by the number of letters that are required to solve the puzzle");
System.out.println("4) In terms of chances, if a player ends up on Bankruptcy, then the turn automatically get shifted to the next player. Each game features a number of 2 Toss-Up puzzles, which reveal the puzzle one letter at a time and award cash to whoever rings in with the right answer. The player must have atleast 250 dollars to guess a vowel and if the player does not have 250 dollars, the player will have to choose a option again.");
}

else if (choice == 3)
{

}
}
}


View Tutorial          By: Ridge Fernandes at 2012-01-19 04:09:45
12. View Comment

can someone explain above example in detail

View Tutorial          By: neha at 2012-03-24 05:57:34
13. View Comment

org.replaceAll("is","was"); enough to replace all is with the was.

View Tutorial          By: nirosha at 2013-01-28 16:19:11
14. View Comment

import java.io.*;
class CharaaDemofromnet
{
public static void main(String args[])throws IOException
{

char arr[]={'a','b','c'};
String s = new String(arr);
int v=s.length();
for(int k=0;k<v;k++)
{
for(int j=0;j<v;j++)
{
for(int i=0;i<v-j-k;i++)
{
System.out.print(arr[i]);
}
System.out.println();
}
}
}
}


View Tutorial          By: bond at 2014-08-16 17:02:10

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Fazal
The Tag Life Cycle with Attributes in JSP
Using Shift Operators in C
IncludeAction in Struts
typedef example program in C
Arithmetic Evaluation Using the Expression Language in JSP
Tutorial on Complicated Declarations in C
Static Variables in C
getPosition() the right strategy in getting GPS
Precedence and Order of Evaluation in C
File Copying in C
JSF Life Cycle
Getting User Input Using cin in C++
UDP Datagram sample in J2ME
GUI components and menu based J2ME Applications.
A Serialization Example in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
Student marks calculation program in Java
TCP Server and TCP Client in Java
FileReader and FileWriter example program in Java
Integer: byte, short, int, and long data types in Java
XML and Java - Parsing XML using Java Tutorial
How to Send SMS using Java Program (full code sample included)
Count number of vowels, consonants and digits in a String in Java
Multidimensional or arrays of arrays in Java
Vector example in Java
String Class Constructors in Java
Calculate gross salary in Java
append() in Java
Using One-Dimensional Arrays in Java
indexOf( ) and lastIndexOf( ) in Java
How to use equals( ) and equalsIgnoreCase( ) in Java
Most Emailed Articles (in Java)
What is Java?
Read from a COM port using Java program
inheritance in Java
Update contents of a file within a jar file
Using PrintWriter in Java
Booleans in java
How to Send SMS using Java Program (full code sample included)
emulator 0 terminated while waiting for it to register!
package com.sun.speech.freetts does not exist.
Recursion in java
The java Buzzwords
Execute system commands in a Java Program
Handling Fractions in Java
Summary of Operators in Java
Use of return statement in Java