Reverse Words String Program in Java
Hello Friends, Today I want to
share with you one new program in java. How to write a reverse word string program
in java. Before starting the program we understand that What is String In Java. String is a collection of characters.
example: "market". This is an example of a Java String.
So now we want to understand
how to create strings in Java.
String str = "Hello Java I
am a String";
Java String is Immutable.
It Means once we defined the string in the object. It can't be changed.
In This program we use the
string split method So now we understand what is string split method
String Split Method: split() method is used to split a string into an array of
substrings.
If an empty string ("") is used as the
separator, the string is split between each character
The split() method does not change the original
string.
Syntax of String Split:
var str="Hello Java I am a developer";
var words = str.split(" ");
Now we understand what is for loop because for loop is also
used two time in this program. Basically For loop is used for repeation code of
several time and iteration is also fixed in for loop.
Syntax for
Loop:
for(initiation;condition;incriment/decriment){
// code to be executed
}
String CharAt
Method: In this program, we also used String CharAt method
so now we understand what is charAt method returns a char value at the given
index number. The index of the first
character is 0, the second character is 1, and so on.
Syntax:
public char charAt(int index)
Program Algorithm
or Process:
1. First we make a package like com;
2. Make a public class
with a specific name of class.
3. In this class we make one method declare with void and
argument str.
4. Then we define string array with string split method
5. Create an empty string.
6. Iterate the for loop
till word length.
7. We declare one more string words in the inside for loop.
8. Now we reverse word and decrement one by one.
9. Now we find a particular word position and add with the word.
10. Now we add with words with reverse string.
11. We make the main method and access a method with a help object.
12. Now we see the print of our final output.
Program:
package com;
public void reverseString(String str)
{
String []words = str.split(" ");
String reversedStrig= "";
for(int i=0;i<words.length;i++)
{
String word=words[i];
String reversedWord="";
for(int j=word.length()-1;j>=0;j--)
{
reversedWord=reversedWord + word.charAt(j);
}
reversedStrig=reversedStrig + reversedWord+" ";
}
System.out.println(str);
System.out.println(reversedStrig);
}
public static void main(String[] args) {
RevesreWordString
ob1=new RevesreWordString();
ob1.reverseString("Hello Java I
am developer");
}
}
Output:
Hello Java I am developer
olleH avaJ I ma repoleved
Previous Program You May also like:
Write a JAVA Program for Check Year is leap
No comments:
Post a Comment