aspose file tools
The moose likes Beginning Java and the fly likes manipulating words in a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Groovy Fundamentals video training course this week in the Groovy forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "manipulating words in a string" Watch "manipulating words in a string" New topic

manipulating words in a string

[snap] lo-brow

Joined: Sep 21, 2003
Posts: 2
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
class StringProgram {

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

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


String ans = Key.readLine();


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

Joined: Jun 09, 2003
Posts: 4632
String firstWord = ans.substring(0,ans.indexOf(" "));
String lastWord = ans.substring(ans.lastIndexOf(" ")+1);
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

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!

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
[snap] lo-brow

Joined: Sep 21, 2003
Posts: 2
Thanks alot for your help,
and I will change my name for the next post
I agree. Here's the link:
subject: manipulating words in a string