Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

manipulating words in a string

 
[snap] lo-brow
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody
I am new to java and programming in general
the program I am attempting to write requires me to have a user type in short string of text. I then make several manipulations to both the first and last words, such as swapping them, changing their case etc. The string can be any short sting of text.
What I need help with is identifying the first and last words words in the string. Because I cannot anticipate what will be typed in, and the only way I really know to specify a substring is using indexof(), I cannot specify the last word.
this is what I have so far
***************************************************************************
import java.io.*;
class StringProgram {

public static void main (String[] args) throws Exception
{
BufferedReader Key = new BufferedReader (new InputStreamReader (System.in));

System.out.println("Please Type in a short line of text");

System.out.print(">");

String ans = Key.readLine();

System.out.println(ans);

System.out.println("The length of your line of text was " + ans.length() + " characters");

int step_1 = ans.indexOf(' ');

System.out.println("The first word has " + step_1 + " characters");
***************************************************************************

and this is where I get stuck because while I know how to perform the desired modifications, I do not know how to specify the words in the string I want to modify, or if I am even on the right track
thanks so much for any help, this looks like a great forum
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String firstWord = ans.substring(0,ans.indexOf(" "));
String lastWord = ans.substring(ans.lastIndexOf(" ")+1);
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by [snap] lo-brow:
thanks so much for any help, this looks like a great forum

Welcome to JavaRanch, lo-brow!
This is a great forum, but one of the things that makes it great is our professional demeanor. To further that image, we ask that you please change your display name to comply with The JavaRanch Naming Policy. (We are looking for a first name, a last name of at least two letters (and preferrably containing a vowel...) and names that are not obviously fictitious.)
Thanks Pardner! Hope to see you 'round the Ranch!
 
[snap] lo-brow
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot for your help,
and I will change my name for the next post
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic