Java program to reverse a string not working? - java

I have written a piece of code to reverse a string in Java. However, its showing multiple errors and I wish to understand where it is that I am going wrong. I know that there are alternative methods of reversing a string. However, I want to know where I am going wrong with my code.
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
Errors:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
Could someone provide me with a resolution?

There are many errors in your code :
For loop condition should be i < len
String rev should be initialized to "" (empty string), else it will throw error when you try to append another string to it.
You can't access characters in a string using str[i], use str.charAt(i) instead.
You are trying to initialize a function (Reverse) inside another function (main), you must initialize it outside the main function.
Also, here is a simple one liner for string reversal:
new StringBuilder(str).reverse().toString()
A good tip might be to use the StringBuilder class whenever you want to do any kind of string manipulation in Java.

Your code has many issues:
You are declaring the method Reverse() inside the main method.
You also need to initialize rev to an empty string.
You can use str.charAt(i) to access each character of the string.
Your for loop goes beyond the string if you use i <= len; so it
should be i < len;.
Your Reverse() method should be static since you are calling it in main
method (which is static)
Here is working code.
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}

Please see the below code:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}

public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}

Related

Creating a new string made of every other character of a given array, and returns it

Need to create a method in which, given a string, a new string will be made and returned formed out of every other character in the original string.
public static String everyOther(String str) {
String result = "";
for (int i=0; i<A.length; i+=2){
result = result + str.charAt(i);
}
System.out.println(result);
return result;
}
public static void main(String[] args) {
String G = "abcdefghijklmnopqrstuvwxyz";
System.out.println(everyOther(G));
}
Your everyOther method should read
public static String everyOther(String str) {
String result = "";
for (int i=0; i < str.length(); i+=2){
result += str.charAt(i);
}
return result;
}
Your for loop was slightly off (see my comment on OP), and there is no need to print out your result ehre as you do that in your main function - unless ofcourse you wanted to print it out twice

Java: Return an int out of a var, containing letters and figures

i hope someone can help me, i have the following problem.
I have a variable that looks like this:
var a = "01VENT000KRV010WFEVVV055";
I would like to either:
have the last 3 figures of the variable (e.g. 055) as an int
or remove ALL non-figures out of the variable (e.g. 01000010055) as an int
My idea was that:
int sub = Integer.parseInt(a.substring(a.length-3));
or:
int sub = Integer.parseInt(a.replaceAll("[\\D]", ""));
That didnt work, so i would really appreciate if someone could help me here
Thanks
Note all methods can potentially return an empty string.
public static void main(String[] args) {
// TODO code application logic here
String a = "01VENT000KRV010WFEVVV055";
System.out.println(removeChars(a));
System.out.println(removeDigits(a));
System.out.println(getLastThreeChars(a));
}
//This method removes Characters from a string and returns a String of numbers
static String removeChars(String t)
{
String tempString = "";
for(int i = 0; i < t.length(); i++)
{
if(Character.isDigit(t.charAt(i)))
{
tempString += t.charAt(i);
}
}
return tempString;
}
//This method removes Digits from a string and returns only characters
static String removeDigits(String t)
{
String tempString = "";
for(int i = 0; i < t.length(); i++)
{
if(Character.isAlphabetic(t.charAt(i)))
{
tempString += t.charAt(i);
}
}
return tempString;
}
//This methods prints the last 3 char of a string
static String getLastThreeChars(String t)
{
StringBuilder tempString = new StringBuilder();
for(int i = t.length() - 1; i > t.length() - 1 - 3; i--)
{
tempString.append(t.charAt(i));
}
return tempString.reverse().toString();
}

Simple Java String Reversal

I'm having trouble with this problem.
Here is the code I wrote out:
package com.jdewey.rvrs;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your string: ");
String userIn = console.nextLine();
int inLength = userIn.length();
stringRvrs(userIn, inLength);
}
public static void stringRvrs(String x, int length){
for(int i = 1; i <= length; i++){
int y = -1 * i + length;
System.out.print(x.substring(y));;
}
}
}
It's supposed to output "tset" if you were to input "test"
Please help!
It makes more sense to just write your loop to start at the end of the string, and also to print each character using charAt instead of substring. See below:
public static void stringRvrs(String x, int length){
String result = "";
for(int i = length - 1; i >= 0; i--){
result = result + x.charAt(i);
}
System.out.println(result);
}
Of course, there is an easier way using library functions to reverse a string (see here: Reverse a string in Java), but I assume this is a learning exercise for you so I corrected the code instead of just linking to an easy way to do it.
Try StringBuilder as in:
public static void stringRvrs(String x){
char [] all = x.toCharArray();
StringBuilder concate = new StringBuilder();
for(int i = all.length-1;i >= 0;i--){
concate = concate.append(String.valueOf(all[i]));
}
System.out.println(x+" reversed to "+concate);
}
No need to pass int length as an parameter to the method.
you can simply use stringBuilder.reverse();
your method should look like this after the changes,
public static void stringRvrs(String x, int length){
StringBuilder sb = new StringBuilder(x);
System.out.println(sb.reverse());
}
There is no need to pass the length of the String as an argument since it can be found using string.length(); at any point of time.

Displaying a string backwards using substring

I have here a method that displays a string backward.
public static String ReverseStr(String backward) {
String newString = "";
for (int i=0; i<backward.length(); i++) {
newString = backward.charAt(i) + newString;
}
return newString;
}
It works properly but I'd like to do it in another way, that is, using a for loop, getting each character in the string using substring method with two parameters, starting with the last character then concatenates that one-character substring with the new string each time through the loop.
I tried this:
public static String ReverseStr(String backward) {
String newString = "";
for (int i=0; i>backward.length(); i--) {
String subChar = backward.substring(backward.length()-1);
newString += subChar;
}
return newString;
}
But when I run the program, it displays nothing. Please help me fix the code. Thank you very much!
If this is not a homework, then use StringBuilder class and reverse() method.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html#reverse()
If this is a homework do it by yourself.
The loop never executes due to wrong control condition:
for (int i=0; i>backward.length(); i--)
It starts from 0 and continues until i is greater than length (which is never true as length is always at least 0). You probably meant:
for (int i=backward.length(); i>=0; i--)
Once you manage to fix your code, consider using StringBuilder instead of concatenating to String. And once you manage to use StringBuilder, you'll discover handy reverse() method:
return new StringBuilder(backward).reverse().toString();
Your for loop is messed up, it will never run since you have the wrong condition, change it to:
for (int i=backward.length(); i>=0; i--)
class Test
{
public static void main(String[] args)
{
String strtorev = "Test Code";
String newString = "";
int len = strtorev.length();
System.out.println(len);
for(int i =0;i<len;i++)
{
String subChar = strtorev.substring(strtorev.length()-1-i,strtorev.length()-i);
newString += subChar;
System.out.println(newString);
}
}
}
You should StringBuilder. The following code should work as you expect.
public static String ReverseStr(String backward)
{
String newString = "";
StringBuilder sb=new StringBuilder(backward);
for (int i=0; i>backward.length(); i--) //backward.length() may be replaced with sb.length()
{
String subChar = sb.charAt(i); //Replace `substring()` with `charAt()`
newString += subChar;
}
return newString;
}
public static String ReverseStr(String backward) {
String newString = "";
for (int i=backward.length()-1; i>=0; i--)
newString+ = backward.charAt(i);
return newString;
}
We can use recursion to reverse a String
public class ReverseStringTest {
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
}
//Calling Function Recursively
return reverseString(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
System.out.println(reverseString("java"));
}
}

How can I split a string into words in Java without using String.split()?

My teacher specifically requested that we split a sentence into words without using String.split(). I've done it using a Vector (which we haven't learned), a while-loop, and substrings. What are other ways of accomplishing this? (preferably without using Vectors/ArrayLists).
I believe that your teacher is asking you to process the string yourself (without using any other libraries to do it for you). Check to see if this is the case - if you can use them, there are things such as StringTokenizer, Pattern, and Scanner to facilitate string processing.
Otherwise...
You will need a list of word separators (such as space, tab, period, etc...) and then walk the array, building a string a character at a time until you hit the word separator. After finding a complete word (you have encountered a word separator character), save it the variable out into your structure (or whatever is required), reset the variable you are building the word in and continue.
Parsing the string character by character, copying each character into a new String, and stopping when you reach a white space character. Then start a new string and continue until you reach the end of the original string.
You can use java.util.StringTokenizer to split a text using desired delimiter. Default delimiter is SPACE/TAB/NEW_LINE.
String myTextToBeSplit = "This is the text to be split into words.";
StringTokenizer tokenizer = new StringTokenizer( myTextToBeSplit );
while ( tokinizer.hasMoreTokens()) {
String word = tokinizer.nextToken();
System.out.println( word ); // word you are looking in
}
As an alternate you can also use java.util.Scanner
Scanner s = new Scanner(myTextToBeSplit).useDelimiter("\\s");
while( s.hasNext() ) {
System.out.println(s.next());
}
s.close();
You can use java.util.Scanner.
import java.util.Arrays;
public class ReverseTheWords {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(ReverseTheWords.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
YOu can use StringTokenizer
http://www.java-samples.com/showtutorial.php?tutorialid=236
Or use a Pattern (also known as a regular expression) to try to match the words.
Use a Scanner with ctor (String)
regular expressions and match
StringTokenizer
iterating yourself char by char
recursive iteration
Without using a Vector/List (and without manually re-implementing their ability to re-size themselves for your function), you can take advantage of the simple observation that a string of length N cannot have more than (N+1)/2 words (in integer division). You can declare an array of strings of that size, populate it the same way you populated that Vector, and then copy the results to an array of the size of the number of words you found.
So:
String[] mySplit( String in ){
String[] bigArray = new String[ (in.length()+1)/2 ];
int numWords = 0;
// Populate bigArray with your while loop and keep
// track of the number of words
String[] result = new String[numWords];
// Copy results from bigArray to result
return result;
}
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class sha1 {
public static void main(String[] args) {
String s = "hello java how do you do";
System.out.println(Arrays.toString(sha1.split(s)));
}
public static String[] split(String s) {
int count = 0;
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
count++;
}
}
String temp = "";
int k = 0;
String[] rev = new String[count + 1];
for (int i = c.length-1; i >= 0; i--) {
if (c[i] == ' ') {
rev[k++] = temp;
temp = "";
} else
temp = temp + c[i];
}
rev[k] = temp;
return rev;
}
}
Simple touch.! Improve if you want to.
package com.asif.test;
public class SplitWithoutSplitMethod {
public static void main(String[] args) {
split('#',"asif#is#handsome");
}
static void split(char delimeter, String line){
String word = "";
String wordsArr[] = new String[3];
int k = 0;
for(int i = 0; i <line.length(); i++){
if(line.charAt(i) != delimeter){
word+= line.charAt(i);
}else{
wordsArr[k] = word;
word = "";
k++;
}
}
wordsArr[k] = word;
for(int j = 0; j <wordsArr.length; j++)
System.out.println(wordsArr[j]);
}
}
Please try this .
public static String[] mysplit(String mystring) {
String string=mystring+" "; //append " " bcz java string does not hava any ending character
int[] spacetracker=new int[string.length()];// to count no. of spaces in string
char[] array=new char[string.length()]; //store all non space character
String[] tokenArray=new String[string.length()];//to return token of words
int spaceIndex=0;
int parseIndex=0;
int arrayIndex=0;
int k=0;
while(parseIndex<string.length())
{
if(string.charAt(parseIndex)==' '||string.charAt(parseIndex)==' ')
{
spacetracker[spaceIndex]=parseIndex;
spaceIndex++;
parseIndex++;
}else
{
array[arrayIndex]=string.charAt(parseIndex);
arrayIndex++;
parseIndex++;
}
}
for(int i=0;i<spacetracker.length;i++)
{
String token="";
for(int j=k;j<(spacetracker[i])-i;j++)
{
token=token+array[j];
k++;
}
tokenArray[i]=token;
//System.out.println(token);
token="";
}
return tokenArray;
}
Hope this helps
import java.util.*;
class StringSplit {
public static void main(String[] args)
{
String s="splitting a string without using split()";
ArrayList<Integer> al=new ArrayList<Integer>(); //Instead you can also use a String
ArrayList<String> splitResult=new ArrayList<String>();
for(int i=0;i<s.length();i++)
if(s.charAt(i)==' ')
al.add(i);
al.add(0, 0);
al.add(al.size(),s.length());
String[] words=new String[al.size()];
for(int j=0;j<=words.length-2;j++)
splitResult.add(s.substring(al.get(j),al.get(j+1)).trim());
System.out.println(splitResult);
}
}
Time complexity: O(n)
You can use java Pattern to do it in easy way.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
You can also use String.substring or charAt[].

Categories