Here is my code to print string characters reversed in Java without using any API. But it's not working properly. Can anybody help me to correct it?
public static void main(String args[]) {
String input = "I am test";
String result = "";
for (int i = input.length() - 1; i > 0; i--) {
Character c = input.charAt(i);
if (c != ' ') {
result = c + result;
} else {
System.out.println(result + " ");
}
}
}
It is giving output "test amtest", while the output should be "test am I".
Please help me to get exact output without using predefined methods or API's.
There are four problems with your implementation:
You do not go all the way down to zero,
You put an end of line after each printout in the loop,
You do not print the "tail" result after the loop is over, and
You do not clear out result after printing it in the loop.
Fixing these issues will give you proper output (demo).
try
public static void main(String args[]) {
String input = "I am test";
String result = "";
int start=input.length()-1;
for (int i = input.length()-1; i >=0; i--) {
Character c = input.charAt(i);
if (c == ' ') {
for(int j=i+1;j<=start;j++)
result +=input.charAt(j);
result+=" ";
start=i-1;
}
else if (i==0)
{
for(int j=0;j<=start;j++)
result +=input.charAt(j);
}
}
System.out.println(result);
}//It is giving output as test amtest
//output should be : test am I
public static void main(String args[]) {
String input = "I am test";
String result = "";
String[] frags = input.split(" ");
for (int i = frags.length - 1; i >= 0; i--) {
System.out.print(frags[i] + " ");
}
System.out.println();
}
You can try recursion as well -
public static void main(String args[]) {
String input = "I am test";
List<String> listOfString = Arrays.asList(input.split(" "));
System.out.println(reverseString(listOfString));
}
private static String reverseString(List<String> input) {
int n = input.size();
String result = "";
if(input.isEmpty()){
return result;
}
if(n>1){
/*adding last element with space and changes the size of list as well
test + " " + [am, I]
test + " " + am + " " + [I]*/
result = input.get(n-1) + " " + reverseString(input.subList(0, n-1));
}else{
result = input.get(n-1);
}
return result;
}
hope it helps.
public static void main(String args[]){
String input = "I am test";
String result="";
for(int i=input.length()-1;i>=0;i--){
result=result+input.charAt(i);
}
System.out.println(result);
}
Related
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()));
}
}
I'm trying to print some elements in array.My array is like,
prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"}
what I'm trying to print is,
int[] float[][] string[][][]
I've been trying various things and it got messy now..
My code is,
String ps="";
int u=0;
for(int y=0;y<prmArray.length;y=u)
{
String br_string="";
if(prmArray[y].equals("[]")){
int f=y+1;
br_string+="[]";
for(int h=f;h<prmArray.length;h++){
u=h;
if(prmArray[h]=="[]"){
br_string+="[]";
}
else{
u=u-1;
break;
}
}
ps+=prmArray[u+1]+br_string+" ";
u=u+2;
}
else{
ps+=prmArray[y]+" ";
u=u+1;
}
}
System.out.println(ps);
please help..
You can use this function:
public static String formatArray(String[] prmArray){
String result = "";
String tempResult = "";
for (String entry: prmArray){
if(entry.equals("[]")){
tempResult += entry;
}else{
tempResult = entry + tempResult;
//flip tempResult
result += tempResult + " ";
tempResult = "";
}
}
return result;
}
Stack implementation:
import java.util.Stack;
public class Stk {
public static void main(String...orange)
{
String [] prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"};
Stack<String> stack = new Stack<String>();
for (String str : prmArray)
{
if (str.equals("[]"))
stack.push(str);
else
{
while(!stack.isEmpty())
str+=stack.pop();
System.out.print(str + " ");
}
}
}
}
Output:
int[] float[][] string[][][]
If I have well understood what you are trying to do, you don't need nested loops, you can do it in a single pass, putting in your br_string the "[]" you've encountered so far.
When you find something else you build a part of your final result (ps ) and go on ;-)
public static void main(String[] args) {
String[] prmArray={"[]","int","[]","[]","float","[]","[]","[]","string"};
String ps = "";
String br_string="";
for (int i = 0 ; i< prmArray.length ; i++) {
if(prmArray[i].equals("[]")){
br_string += prmArray[i];
} else {
br_string = prmArray[i] + br_string + " ";
ps += br_string;
br_string = "";
}
}
System.out.println(ps);
}
I want to reverse each individual word of a String in Java in different different sitautions (not the entire string, just each individual word).
Example1: if input String is "This is a test" then the output should be "sihT si a tset".
Example2: if input String is "This is a test" then the output should be "sihT si a tset".
[When there is more than one space between some words]
Please also provide algorithm for understanding
What I have tried so far
class reverseAString
{
public static void main(String args[])
{
String str= "Test the product";
String strArr[]= str.split(" ");
for(int i=0;i<=strArr.length-1;i++)
{
for(int j=strArr[i].length()-1; j>=0;j--)
{
System.out.print(strArr[i].charAt(j));
}
System.out.printf(" ");
}
}
}
---------
public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";
for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}
return reverse;
}
This approach is much more succinct.
class StringRev{
public static void main(String args[]){
String str[] = "Test the product".split(" ");
String finalStr="";
for(int i = str.length-1; i>= 0 ;i--){
finalStr += str[i]+" ";
}
System.out.println(finalStr);
}
}
public static void main(String arg[]) {
System.out.println(reverseWords("This is a test"));
}
// function to reverse each word
public static String reverseWords(String input) {
String result = null;
StringBuffer strBuffer = new StringBuffer();
String split[] = input.split(" ");
for (String temp : split) {
if (temp != " ") {
strBuffer.append(reverse(temp));
strBuffer.append(" ");
} else {
strBuffer.append(" ");
}
}
result = strBuffer.toString();
return result;
}
// function to reverse individual word
public static String reverse(String input) {
StringBuffer strBuffer = new StringBuffer();
char[] charArray = input.toCharArray();
for (int j = charArray.length - 1; j >= 0; j--) {
strBuffer.append(charArray[j]);
}
return strBuffer.toString();
}
Split complete string on basis of space
Then convert each string to character array and reverse
individual word.
It's been a long time since I've touch Java, but here's the algorithm.
String stringToReverse = "This is a Test";
String finalString = "";
Stack word = new Stack;
for(int i = 0; i < stringToReverse.length; i++){
char chr = stringToReverse[i];
if(chr == " " || i == (stringToReverse.length - 1)){
while(word.count > 0){
finalString += word.pop();
}
finalString += chr;
}else{
word.push(chr);
}
}
If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.
public class test {
public static void main(String args[]) {
String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
int wordLengthCount [] = new int [20];
String wordCountText = "";
String sentence[] = text.split("[,\\-:\\?\\!\\ ]");
for (int i = 0; i < sentence.length; i++)
{
wordLengthCount[sentence[i].length()]++;
}
for(int wordLength=0; wordLength<sentence.length; wordLength++)
{
if (wordLengthCount[wordLength] != 0){
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
System.out.println(wordCountText);
}
}
You need to iterate over all wordLengthCount
Quick fix:
for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
if (wordLengthCount[wordLength] != 0) {
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
Live demo
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] +" ");
}
}
}