I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}
Related
I have a string "Hello, World!" that I have to convert into a char array. I then found the index of the char ',' - to which I want to create a new char array that contains " World!, Hello".
I've got the first index of the char array moved to the back - such that it prints out "ello, World!H".
How can I use my variable indexDelimiter to move the rest of the char arrays (as well as the ',') to the back? I've been looking at this problem forever, and I'm very confused as to how I could go about this.
I can't use ListArray. I has to be an Array.
public class ArrayTest {
public static void main(String[] args) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
for (int i = 0; i < oldCharArray.length - 1; i++) {
newCharArray[i] = oldCharArray[i + 1];
}
newCharArray[oldCharArray.length - 1] = oldCharArray[0];
for (int i = 0; i < newCharArray.length; i++) {
System.out.print(newCharArray[i]);
}
// This prints out "ello, World!H" but I want " World!, Hello"
}
}
This code will produce "World!,Hello", take a look and see if it meets your needs.
public static void main(String args[]) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
int i = 0;
for (i = 0; i < oldCharArray.length-indexDelimiter-1; i++) {
newCharArray[i] = oldCharArray[indexDelimiter + i + 1];
}
newCharArray[i] = delimiter;
i++;
int j = i;
while (i < oldCharArray.length) {
newCharArray[i] = oldCharArray[i - j];
i++;
}
System.out.println(newCharArray);
}
If you mean backward, you can reverse the by splitting it first
public char[] reverse_comma_split(String str) {
String[] spl = str.split(",");
String reversed = new String();
for (int i = spl.length - 1; i >= 0; i--) {
reversed += spl[i];
if (i != 0)
reversed += ", ";
}
return reversed.toCharArray();
}
Calling reverse_comma_split("Hello, world!") would return a char array of " world!, Hello"
However, if you insist to get uppercase char in every split, you can modify the loop in which spl[i] to spl[i].substring(0, 1).toUpperCase() + spl[i].substring(1)
public class App {
public static void main(String[] args) {
getWords("i m very very happy");
}
private static TreeSet<String> getWords(String str) {
char a[] = str.toCharArray();
String smallWords = "";
List<String> words = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (a[i] != ' ') {
smallWords = smallWords + a[i];
} else {
char sortedA[] = smallWords.toCharArray();
Arrays.sort(sortedA);
String sortedString = new String(sortedA);
words.add(sortedString);
smallWords = "";
}
}
System.out.println("words :: " + words);
TreeSet<String> sortedWords = new TreeSet<>(words);
System.out.println("sortedWords :: " + sortedWords);
return sortedWords;
}
}
In above code I was able to code the right output with every word sorted of a string array but my output was [ervy, i, m] where last word happy is missing. Can someone please guide what logic I have to use so last word of the array should also reflect in my output.
As #sprinter commented: "he code that adds sortedString to words is only executed when you reach a space in the string. Given there's no space at the end of the string it's never executed for the final word."
One option to fix that would be to break your if statement up into the piece that handles spaces and the piece that processes the words.:
for (int i=0; i < a.length; i++) {
// if not space add to smallWords
if (a[i] != ' ') {
smallWords = smallWords + a[i];
}
// if space or last character, process smallWords
if (a[i] == ' ' || i==a.length-1) {
char sortedA[] = smallWords.toCharArray();
Arrays.sort(sortedA);
String sortedString = new String(sortedA);
words.add(sortedString);
smallWords = "";
}
}
result:
words :: [i, m, ervy, ervy, ahppy]
sortedWords :: [ahppy, ervy, i, m]
Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();
I have to capitalize the first letter in every word passed into the string. My output is doing that capitalization, but it's not maintaining the format of the original output. For example, string input is "hello world", my output is "HelloWorld", and my desired output should be "Hello World."
I've tried to add spaces where I can throughout the code but nothing works. I think the problem is that when I use toCharArray, it gives me an output with no spaces? So my concatenation result is adding everything in one swoop, versus each word separately?
Or I thought that my code was using string concatenation with my result, and it's not being separated because I have both words going into the same variable.
import java.util.*;
import java.io.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for(int j = 0; j < charWord.length; j++ ) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result += (j == 0 ? cap : word[i].charAt(j));
}
}
return result;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
No errors. Just not getting desired output.
When you did String[] word = str.split(" ");, the space between each word is taken out and you are now left with only the words in an array. You should use String.join(" ", word) on the resultant words array to reverse the effects so you get the spaces back.
Instead of going through each word char by char, try this:
for(int i = 0; i < word.length; i++) {
word[i] = word[i].substring(0, 1).toUpperCase() + word[i].substring(1);
}
result = String.join(" ", word);
Try this:
import java.util.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
result += capitalize(word[i]) + (i != word.length - 1 ? " " : "");
}
return result;
}
private static String capitalize(String s){
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
You can use the below code.
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for (int j = 0; j < charWord.length; j++) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result.append(j == 0 ? cap : word[i].charAt(j));
}
result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
Can anyone tell me how to write a Java program to reverse a given sentence?
For example, if the input is:
"This is an interview question"
The output must be:
"question interview an is this"
You split the string by the space then iterate over it backwards to assemble the reversed sentence.
String[] words = "This is interview question".split(" ");
String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
rev += words[i] + " ";
}
// rev = "question interview is This "
// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
revb.append(words[i]);
revb.append(" ");
}
// revb.toString() = "question interview is This "
String[] words = sentence.split(" ");
String[] reversedWords = ArrayUtils.reverse(words);
String reversedSentence = StringUtils.join(reversedWords, " ");
(using ArrayUtils and StringUtils from commons-lang, but these are easy methods to write - just a few loops)
Just being different: a recursive solution. Doesn't add any extra spaces.
public static String reverse(String s) {
int k = s.indexOf(" ");
return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
}
System.out.println("[" + reverse("This is interview question") + "]");
// prints "[question interview is This]"
I will also improve on the split solution by using \b instead (it's so obvious!).
String[] parts = "Word boundary is better than space".split("\\b");
StringBuilder sb = new StringBuilder();
for (int i = parts.length; i --> 0 ;) {
sb.append(parts[i]);
}
System.out.println("[" + sb.toString() + "]");
// prints "[space than better is boundary Word]"
Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:
To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.
(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).
Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.
String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
output += array[i];
if (i != 0) { output += " "; }
}
a every boring bit of java:
List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
Collections.reverse(l);
StringBuffer b = new StringBuffer();
for( String s : l ){
b.append(s).append(' ');
}
b.toString().trim();
in groovy it's a little bit more readable:
"this is an interview question"
.split("\\s")
.reverse()
.join(' ')
I also give it a try: Here's a version using a stack and a scanner:
String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();
while(sc.hasNext()) {
stack.push(sc.next());
}
StringBuilder output = new StringBuilder();
for(;;) { // forever
output.append(stack.pop());
if(stack.isEmpty()) {
break; // end loop
} else {
output.append(" ");
}
}
public class ReverseString {
public void reverse(String[] source) {
String dest = "";
for (int n = source.length - 1; n >= 0; n--) {
dest += source[n] + " ";
}
System.out.println(dest);
}
public static void main(String args[]) {
ReverseString rs = new ReverseString();
String[] str = "What is going on".split(" ");
rs.reverse(str);
}
}
nicer approach probably.. had seen the logic somewhere..here is my code which might do the job.
public class revWords {
public static void main(String[] args) {
revWords obj = new revWords();
String print = obj.reverseWords("I am God");
System.out.println(print);
}
public String reverseWords(String words)
{
if(words == null || words.isEmpty() || !words.contains(" "))
return words;
String reversed = "";
for( String word : words.split(" "))
reversed = word + " " + reversed;
return reversed;
}
}
I don't think you should use any library..
1) Reverse whole string
2) Reverse each word.
public static void revWord(char[] a) {
// reverse whole
revWord(a, 0, a.length);
int st = -1;
int end = -1;
for (int i = 0; i < a.length; i++) {
if (st == -1 && a[i] != ' ') {
st = i;
}
if (end == -1 && a[i] == ' ' ) {
end = i;
}
if(i == a.length-1){
end=i+1;
}
if (st != -1 && end != -1) {
revWord(a, st, end );
st = -1;
end = -1;
}
}
}
public static void revWord(char[] a, int s, int l) {
int mid = (l - s) / 2;
l--;
for (int i = 0; i < mid; i++, l--) {
char t = a[s+i];
a[s+i] = a[l];
a[l] = t;
}
}
`
No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:
String input = "This is interview question";
List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
please try below solution, this is working for me.
public class reverseline {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="This is interview question";
String words[]=str.split(" ");
for(int i=words.length-1;i>=0;i--){
System.out.print(words[i]+" ");
}
}
}
Before StringTokenizer was declared legacy, many used StringTokenizer for this. Thought I would just leave it here.
String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence);
while (tokens.hasMoreTokens()) { // Loop through each token
reversed = tokens.nextToken() + ' ' + reversed; //add to start
}
System.out.println(reversed.trim());
Shortest Answer
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
List<String> reverseWord = Arrays.asList(words);
Collections.reverse(reverseWord);
Iterator itr = reverseWord.iterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
OR
public class ReverseSentence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String inputString = sc.nextLine();
String[] words = inputString.split(" ");
for (int i = words.length-1 ; i >= 0; i--) {
System.out.print(words[i] +" ");
}
}
}