tokenize the sentence by using space as a delimiter, save each letter in an array then print out the result in reverse
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
Here's my example
String Str = "The cake is a lie";
char delimiter = ' '; //the space is the delimeter
// calculate the number of delimiter characters
int N = 0;
for (int i = 0; i < Str.length(); i++)
if (Str.charAt(i) == delimiter) N++;
String[] tokens = new String[N+1]; //we add 1 for the last word
int[] tokenlength = new int[N+1];
// parse N+1 tokens and store in an array
int a = 0, b = 0;
for (int i = 0; i < N; i++) {
while(Str.charAt(a) != delimiter)
a++;
tokens[i] = Str.substring(b, a); //saves the word in the array
tokenlength[i] = tokens[i].length(); //saves the length of the current word
a++;
b = a;
}
//For the last word
tokens[N] = Str.substring(a, Str.length());
tokenlength[N] = tokens[N].length();
// print results for testing
System.out.println(Str);
for (int i = 0; i < tokens.length; i++){
// print each tokens in reverse
for(int j = tokenlength[i]-1; j >= 0; j-- ){
System.out.print(tokens[i].charAt(j));
}
System.out.print(" ");
}
Also next time wrap your code in[code] tags
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
Thank you so much it is working, can i know about the how to write the code ?
@zeroliken:
This is why you should never just post a solution to someone else's homework. You have successfully given the OP an opportunity to cheat, but taught him nothing. Next time please help the OP to learn how to solve their own problem and write their own code.
ps; If you must post code please indent it, and follow the normal Java conventions for variable names. Your post was not a good example for beginners.
JamesCherrill
Posting Genius
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
I wrote it as a possible example on how to tokenize a sentence and view it in reverse where he might get a hint on how to do it by himself
sigh, looks like the intention shadowed the purpose :(
Sorry about that...I'll be more conscious next time around
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162