Reversing a String Without Reverse Function or loops - java

So I have to reverse a string but like an example would be reverse Hello World. Well my code reverses it like this dlroW olleH and you have to reverse it like World Hello. This is my code below can someone help me fix it or tell me what im doing wrong please. I need to do as you create a new object and input the data through the object and then call the method.
public class reverseMe {
public String reverseMe(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
}
}

What do you mean for "without reverse function or loops". First of all in java are called methods, not functions, and second in some way you need to iterate the strings. This code just does the job with a recursive method. Call it from your constructor and you’re done. There aren't any already built-in java methods to do what you want.
public class HelloWorld{
public String recursiveReverse(String[] words,StringBuilder b,int length){
if (length < 0)
return b.toString();
else{
b.append(words[length] + " ");
length--;
return recursiveReverse(words,b,length);
}
}
public String reverse (String input){
String[] words = input.split(" ");
StringBuilder reverse = new StringBuilder();
return recursiveReverse(words,reverse,words.length-1);
}
public static void main(String []args){
HelloWorld a = new HelloWorld();
System.out.println(a.reverse("hello this is a test reverse this string"));
}
}
Output:
string this reverse test a is this hello

This answer assumes the following:
Can't use built-in reverse() function, such as found on StringBuilder and Collections.
Can't use loops.
Input can contain any number of words.
Words are separated by a single space.
First, the easiest solution would be to split() the input and then use Stream logic to combine the words in reverse order, however I consider Stream logic to be "Loop logic", so that won't do.
That leaves the use of a recursive method as a solution, similar to the attempt in the question:
static String reverseWords(String input) {
int idx = input.indexOf(' ');
if (idx == -1)
return input;
return reverseWords(input.substring(idx + 1)) + ' ' + input.substring(0, idx);
}
Test
System.out.println(reverseWords("Hello World"));
System.out.println(reverseWords("The quick brown fox jumps over the lazy dog"));
Output
World Hello
dog lazy the over jumps fox brown quick The

We can you use code, however instead of CharAt, we can use it for loops. My method does require java.util.Arrays; to get a subset of the given array. Note, you will have to do reverseMe(str.split(" ")) to run it.
import java.util.Arrays;
public class reverseMe {
public String reverseMe(String[] s) {
if(s.length == 0)
return "";
return s[s.length - 1] + " " + reverseMe(Arrays.copyOfRange(s,0,s.length-1));
}
}
Input: "Hello Newer World"
Output: "World Newer Hello"

Since you can't use any loops or reverse methods, that would leave a recursive method.
However, this is not very efficient.
It works by repeatedly splitting on string less the last word of the previous string and then returning a new String in reversed order.
ReverseMe r = new ReverseMe();
String reversed =r.reverseMe("This is a test of reversing a string");
System.out.println(reversed);
public String reverseMe(String s) {
String arr[] = s.split("\\s+");
if (arr.length > 1) {
return arr[arr.length-1] + " " + reverseMe(s.substring(0, s.lastIndexOf(" ")));
}
return arr[arr.length-1];
}
Prints
string a reversing of test a is This

Related

how to print the longest of three strings?

Is there a quick way to select the longest of three strings (s1,s2,s3) using if/else method?
I'm using Java
I have tried using something like this
if (s1.length() > s2.length()) {
System.out.println(s1); ...
but did not get it right.
Don't try to program all possible combinations with an if-else construct, as the complexity will grow exponentially if you add more strings.
This solution works well for a small number of strings with a linear complexity:
string longest = s1;
if (s2.length() > longest.length()) {
longest = s2;
}
if (s3.length() > longest.length()) {
longest = s3;
}
System.out.println(longest);
For a lager number of strings, put them in collection and find the longest using a loop.
You can use if, else if, else in C# (if you aren't actually using Java which it looks like you are) to handle this.
string current = str;
if(str2.Length > current.Length)
{
current = str2;
}
if (str3.Length > current.Length)
{
current = str3;
}
Unless using if/else is a requirement of this code, using a collection and LINQ will be a cleaner option.
List<string> strList = new List<string>
{
"str",
"strLen",
"strLength"
};
// This aggregate will return the longest string in a list.
string longestStr = strList.Aggregate("", (max, cur) => max.Length > cur.Length ? max : cur);
string a = "123";
string b = "1322";
string c = "122332";
if (a.Length > b.Length && a.Length > c.Length)
{
Console.WriteLine(a);
}
else if (b.Length > c.Length)
{
Console.WriteLine(b);
}
else
{
Console.WriteLine(c);
}
}
if/then/else constructs Java is same as C#. you can use solutions above. LINQ is like Streams in Java. In Java you can code:
public static void main(String args[]) {
printtLongest ("VampireApi","C#-Api","Java Api");
}
public static void printtLongest(String ... strings){
java.util.Arrays
.stream(strings)
.sorted(java.util.Comparator.comparingInt(String::length).reversed())
.findFirst().ifPresent(System.out::println);
}
create an array and input a string into each part of the array(can do this through loop or manually add- String[] st= new st String[]; then you can: st[0]="aaa"; st[1]="eff"... after this you can use a loop which takes the current length of the string at the array[i] and use a variable max(which will start at 0) which keep the highest length using the Math.max() function.
if the length(which is an integer) is larger then max then you save the string in a string variable and the loop will go through every string In your array and will update the max if needed. after this you can either return or print the string which is the longest.
this is one of many ways. or you could do three if's to check. this method would work great with larger amount of strings.
Not using if-else as the OP asked, but a cleaner solution is this:
void longest(String a, String b, String c) {
String[] triplet = {a, b, c};
Arrays.sort(triplet, Comparator.comparingInt(String::length));
System.out.println(triplet[2]);
}

return the first word in any string (Java)

I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );

Recursive removal of characters in Java

As an exercise, the code block below intends to recursively go through a string and remove all the of the "x" characters. It does that, but I would like to keep track of the newStr without passing it as a parameter in the method. Is there anyway to move it into the method body?
Thanks!
public static String deathToX(String str, String newStr) {
//look for x char
if(str.substring(0, 1).equals("x")) {
//do nothing
} else {
//add non-x char to newStr
newStr += str.charAt(0);
}
if(str.length() == 1) {
return newStr;
}
return deathToX(str.substring(1), newStr);
}
public static void main(String[] args) {
System.out.println("Return: " + deathToX("xnoxmore", ""));
}
Well, you could change the code to:
public static String deathToX(String str)
{
// Termination case
if (str.length() == 0)
{
return str;
}
// Work out whether or not we want the first character
String prefix = str.startsWith("x") ? "" : str.substring(0, 1);
// Let the recursive call handle the rest of the string, and return
// the prefix (empty string or the first character) followed by the
// x-stripped remainder.
return prefix + deathToX(str.substring(1));
}
Is that the sort of thing you were thinking of?
Of course, this is a horribly inefficient way of doing string manipulation, but I assume you're more interested in the recursive nature of things.
I would like to keep track of the newStr without passing it as a parameter in the method.
Why? Passing the intermediary result into the function is often required in functional-style recursive programming. What I do is make a function that handles the bulk of the work and accepts the accumulator, and make a wrapper function that calls the previous one with the required starter value:
private static String deathToX0(String str, String newStr) {
// the original implementation
}
public static String deathToX(String str) {
return deathToX(str, "");
}
As an aside, you might not want to use a String for the intermediate result because of the copying involved. A StringBuilder would be faster.
The short answer is yes... with recursion typically on the way down the tree you work out the bit at each level in this case blank or the current character. So the return statement should call itself recursively then at the bottom of the tree the answer you wanted is reconstructed by adding together the sections at each level.
public static String deathToX(String str){
if (!str.isEmpty()){
return (str.substring(0, 1).equals("x") ? "" : str.substring(0, 1)) + deathToX(str.substring(1));
}else{
return "";
}
}
public static void main(String[] args){
System.out.println("Return: " + deathToX("xnoxmore"));
}
In the sample above I used the shorthand if format to put it all on one line but you could expand it out. You should be able to see that the recursive function recurses on the return statement and I put in a special case for the last level. If you were to split it and put this levels answer in a local variable e.g. tmp then you would use:
return tmp + deathToX(str.substring(1));
Remember recursion means that the current execution is only paused until the lower ones finish so you can happily store info to recover on your way back up. Hope this helps :)
public class solution {
// Return the changed string
public static String removeX(String input){
if(input.equals("") || input.equals("x"))
return "";
String returnStr="";
removeX(input.substring(1));
for(int i=0;i<input.length();i++)
{
if(input.charAt(i)=='x')
continue;
else
returnStr+=input.charAt(i);
}
return returnStr;
}
}
This is my approach. This code goes to the end of the string, if it gets X as last string, it returns ""(nothing), then it checks the whole substring for "x", if its present in the string, it will continue, else it will append rest character to that string and it goes on.
Finally returns the updated string.!
Hope this helps..!! well, this is my first contribution here :)

How to capitalize the first letter of word in a string using Java?

Example strings
one thousand only
two hundred
twenty
seven
How do I change the first character of a string in capital letter and not change the case of any of the other letters?
After the change it should be:
One thousand only
Two hundred
Twenty
Seven
Note: I don't want to use the apache.commons.lang.WordUtils to do this.
If you only want to capitalize the first letter of a string named input and leave the rest alone:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Now output will have what you want. Check that your input is at least one character long before using this, otherwise you'll get an exception.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.substring(0, 1).toUpperCase() + original.substring(1);
}
Just... a complete solution, I see it kind of just ended up combining what everyone else ended up posting =P.
Simplest way is to use org.apache.commons.lang.StringUtils class
StringUtils.capitalize(Str);
Also, There is org.springframework.util.StringUtils in Spring Framework:
StringUtils.capitalize(str);
String sentence = "ToDAY WeAthEr GREat";
public static String upperCaseWords(String sentence) {
String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
String newSentence = "";
for (String word : words) {
for (int i = 0; i < word.length(); i++)
newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase():
(i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
}
return newSentence;
}
//Today Weather Great
StringUtils.capitalize(str)
from apache commons-lang.
Here you go (hope this give you the idea):
/*************************************************************************
* Compilation: javac Capitalize.java
* Execution: java Capitalize < input.txt
*
* Read in a sequence of words from standard input and capitalize each
* one (make first letter uppercase; make rest lowercase).
*
* % java Capitalize
* now is the time for all good
* Now Is The Time For All Good
* to be or not to be that is the question
* To Be Or Not To Be That Is The Question
*
* Remark: replace sequence of whitespace with a single space.
*
*************************************************************************/
public class Capitalize {
public static String capitalize(String s) {
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static void main(String[] args) {
while (!StdIn.isEmpty()) {
String line = StdIn.readLine();
String[] words = line.split("\\s");
for (String s : words) {
StdOut.print(capitalize(s) + " ");
}
StdOut.println();
}
}
}
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
{
if(s.charAt(i)==' ')
{
c=Character.toUpperCase(s.charAt(i+1));
s=s.substring(0, i) + c + s.substring(i+2);
}
}
t.setText(s);
Actually, you will get the best performance if you avoid + operator and use concat() in this case. It is the best option for merging just 2 strings (not so good for many strings though). In that case the code would look like this:
String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
Its simple only one line code is needed for this.
if String A = scanner.nextLine();
then you need to write this to display the string with this first letter capitalized.
System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
And its done now.
Example using StringTokenizer class :
String st = " hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){
st1=a.nextToken();
f=Character.toUpperCase(st1.charAt(0));
fs+=f+ st1.substring(1);
System.out.println(fs);
}
Solution with StringBuilder:
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
.. based on previous answers
Adding everything together, it is a good idea to trim for extra white space at beginning of string. Otherwise, .substring(0,1).toUpperCase will try to capitalize a white space.
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
}
My functional approach. its capstilise first character in sentence after whitescape in whole paragraph.
For capatilising only first character of the word just remove .split(" ")
b.name.split(" ")
.filter { !it.isEmpty() }
.map { it.substring(0, 1).toUpperCase()
+it.substring(1).toLowerCase() }
.joinToString(" ")
public static String capitalize(String str){
String[] inputWords = str.split(" ");
String outputWords = "";
for (String word : inputWords){
if (!word.isEmpty()){
outputWords = outputWords + " "+StringUtils.capitalize(word);
}
}
return outputWords;
}
Update July 2019
Currently, the most up-to-date library function for doing this is contained in
org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils;
StringUtils.capitalize(myString);
If you're using Maven, import the dependency in your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
The following will give you the same consistent output regardless of the value of your inputString:
if(StringUtils.isNotBlank(inputString)) {
inputString = StringUtils.capitalize(inputString.toLowerCase());
}
Even for "simple" code, I would use libraries. The thing is not the code per se, but the already existing test cases covering exceptional cases. This could be null, empty strings, strings in other languages.
The word manipulation part has been moved out ouf Apache Commons Lang. It is now placed in Apache Commons Text. Get it via https://search.maven.org/artifact/org.apache.commons/commons-text.
You can use WordUtils.capitalize(String str) from Apache Commons Text. It is more powerful than you asked for. It can also capitalize fulle (e.g., fixing "oNe tousand only").
Since it works on complete text, one has to tell it to capitalize only the first word.
WordUtils.capitalize("one thousand only", new char[0]);
Full JUnit class to enable playing with the functionality:
package io.github.koppor;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
#Test
void test() {
assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
}
}
Use this:
char[] chars = {Character.toUpperCase(A.charAt(0)),
Character.toUpperCase(B.charAt(0))};
String a1 = chars[0] + A.substring(1);
String b1 = chars[1] + B.substring(1);
Given the input string:
Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
You can try the following code:
public string capitalize(str) {
String[] array = str.split(" ");
String newStr;
for(int i = 0; i < array.length; i++) {
newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
}
return newStr.trim();
}
I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Java Code:
class Main {
public static void main(String[] args) {
System.out.println("Capitalize first letter ");
System.out.println("Normal check #1 : ["+ captializeFirstLetter("one thousand only")+"]");
System.out.println("Normal check #2 : ["+ captializeFirstLetter("two hundred")+"]");
System.out.println("Normal check #3 : ["+ captializeFirstLetter("twenty")+"]");
System.out.println("Normal check #4 : ["+ captializeFirstLetter("seven")+"]");
System.out.println("Single letter check : ["+captializeFirstLetter("a")+"]");
System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
System.out.println("Null Check : ["+ captializeFirstLetter(null)+"]");
}
static String captializeFirstLetter(String input){
if(input!=null && input.length() >0){
input = input.substring(0, 1).toUpperCase() + input.substring(1);
}
return input;
}
}
Output:
Normal check #1 : [One thousand only]
Normal check #2 : [Two hundred]
Normal check #3 : [Twenty]
Normal check #4 : [Seven]
Single letter check : [A]
IndexOutOfBound check : []
Null Check : [null]
1. Using String's substring() Method
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Now just call the capitalize() method to convert the first letter of a string to uppercase:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
The StringUtils class from Commons Lang provides the capitalize() method that can also be used for this purpose:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
Add the following dependency to your pom.xml file (for Maven only):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Here is an article that explains these two approaches in detail.
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}

Checking to see if a string is a palindrome with String.equals()

I had a question regarding a basic program I was writing said whether a word such as racecar is a palindrome or not.
All my methods which reverse the string, strip the punctuation work but the one that determines if it is a palindrome does not.
/**
* Determines if a series of letters makes a palinedrome
*
* #param str All punctuation and spaces have been removed
* before this method is called.
* #return true if phrase is a palindrome,
* false otherwise.
*/
public boolean isPalindrome(String str)
{
String d = reverseString (str);
return( str.equals (reverseString (str) ) );
}
Okay, I'm not sure what purpose d is meant to serve in your function since it's never used but, if you want to see why your function's not working, just add debug code:
public boolean isPalindrome (String str) {
System.out.println ("DEBUG: original string = '" + str + "'");
System.out.println ("DEBUG: reverse string = '" + reverseString (str) + "'");
if (str.equals (reverseString (str)))
System.out.println ("DEBUG: returning true");
else
System.out.println ("DEBUG: returning false");
return str.equals (reverseString (str));
}
I'd bet money on there being something wrong with your reverseString function (but not much money). These debug statements should give you enough to figure out where the problem lies.
If string reverseString(String string), and all whitespace was removed then checking if something is a palindrome should be
public boolean isPalindrome(String string)
{
return string.equals(reverseString(string));
}
Granted this is case sensitive so if your palindrome definition does not care about casing, then use equalsIgnoreCase instead.
If this does not work, then you may want to check your stripping and reverseString methods again.
Your problem is the reverse string method you have not shown. If that method is working properly then your isPalindrome method should work. All you need to do is fix your reverse string method.
Java does not have a native reverse string method, and I highly recommend you write your own.
Java does, however, have a reverse method for StringBuffer and StringBuilder. StringBuilder is preferred over StringBuffer.
Use the equals method to compare your reversed string to the original string
The code should be like this:
String d = reverseString (str);
return( str.equals (d) );
You don't have to call twice reverseString()
P.S.: StringBuffer has a method that reverses a String.
I'm sure you've already submitted your homework by now, but I'm learning java and needed the practice, so here's my code for you. It uses a char array and reverses that. I'd assume the best way would be to use a StringBuilder, but the intention of your homework is probably to learn to do it yourself:
public class reverseString {
public static void main(String[] args) {
System.out.println("racecar is a palindrome: "+ isPalindrome("racecar"));
}
public static boolean isPalindrome(String str)
{
String d = reverseString (str);
return( str.equals (reverseString (str) ) );
}
private static char[] reverse(char[] input) {
int length = input.length;
char[] reversed = new char[length];
for (int i=0;i<length;i++) {
reversed[length-i-1]=input[i];
}
return reversed;
}
private static String reverseString(String input){
String reversed = new String(reverse(input.toCharArray()));
return reversed;
}
}
Output:
racecar is a palindrome: true
If anyone has any comments on why my code sucks, fire away. I'd appreciate any constructive criticism.

Categories

Resources