This question already has answers here:
How can I get a char array in reverse order?
(10 answers)
Closed 7 years ago.
Question of reverse string without using string function
I didn't get the inner for loop why s.length()-1 ? why -1 ?
its something have to do like multi dimensional arrays?
char ch[]=new char[s.length()];
for(i=0;i < s.length();i++)
ch[i]=s.charAt(i);
for(i=s.length()-1;i>=0;i--)
System.out.print(ch[i]);
found this code but
The indices of a Java String's characters go from 0 to the String's length - 1 (just like the indices of a Java array start in 0, so do the indices of a String).
Therefore in order to print the String in reverse order, the second loop iterates from s.length()-1 to 0. Prior to that, the first loop iterates from 0 to s.length()-1 in order to copy the characters of the String to a character array.
This has nothing to do with multi-dimensional arrays.
I know you asked for the iterative solution explanation. But, I'll give you the recursive explanation.
public static String reverse(String str)
{
if ((str == null) || (str.length() <= 1))
return str;
return reverse(str.substring(1)) + str.charAt(0);
}
Basically, you check every time the str before calling the function. This is called the base case and is used to stop when the job is completed and not get a stack overflow.
Then, afterwards, the functions returns just a section of the original function. At the end, you'll get the str completely reversed as the iterative solution.
Try using the function using System.out.println(reverse("hello"));
Related
How to create a method that will take imput of a String and an integer n and output the String divided into parts consisting of n characters and separated by a blank space? For example, imput String: "THISISFUN", integer:3, result: "THI SIS FUN".
When you answer, can you please really try to explain what each part of the code does? I really want to understand it.
I tried using StringBuilder and the split() method but the problem is that I don't understand how all of that works. Therefore, I ended up kind of thoughtlessly pasting parts of codes from different online articles which doesn't work the best if you want to actually learn something, especially if you simply cannot find any posts about a specific issue. I could only find things like: "how to divide the String into n parts" and "how to ad a space after a specific char" which are sort of similar issues but not the same.
Here is one way to do it:
public static void splitString(String str, int groupSize){
char[] arr = str.toCharArray(); // Split the string into character array ①
// Iterate over array and print the characters
for(int i=0; i<arr.length; i++){
// If 'i' is a multiple of 'groupSize' ②
if(i > 0 && i % groupSize == 0){ ③
System.out.print(" ");
}
System.out.print(arr[i]);
}
}
① Split the string into a character array (so that you can access the characters individually). You can also do it using the charAt() method without splitting the string into an array. Read the Javadoc for more details.
② Check if the loop counter i is a multiple of groupSize
③ Note the use of System.out.print() as we do not want to print a newline. Here you can use a StringBuilder too and print the contents at the end instead of printing the characters inside the loop.
This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 7 years ago.
How to add whichever character between every character of a premade String? (JAVA)
For example, I have the String "Hello world" and I have to add '_' between every character of the String.
Any function or useful code I can use to do it?
I have to do an algorithm that make me output "H_e_l_l_o_ _w_o_r_l_d"
This is what I have:
public String example(String s) {
String s2 = null;
for(int i = 0; i < s.length(); i++){
s2 += s.charAt(i) + (((i+1) == 0) ? " " : "-");
}
return s2;
}
My output in the main class is being:
nullH-e-l-l-o- -w-o-r-l-d-
Don't know why
This looks like a homework assignment. So, I won't directly write out all the code.
String = "hello world";
Say, there is a variable len = str.length() - 1. Instead of doing it from index 0, we will start our for loop from len - 1. The character 'd' is at index len, and the '_' will have to be inserted right before that. This can be done by setting the string to str = str.substring(0,i) + "_" + str.substring(i+1);
You will have to use a for loop that starts from len - 1 and goes on till the index reached is 0.
Now, on every single iteration, when you are inserting a character assigning str to str.substring(0,i) + "_" + str.substring(i+1); causes you to make a new string object, which is absolutely horrible style. This can be solved by using a StringBuilder.
Does that make it clear?
In the future, refrain from posting questions without having done any work. This community is there to help you with solving issues that you may have in your solutions, not write your solutions for you.
This question already has answers here:
In Java, how do I check if a string contains a substring (ignoring case)? [duplicate]
(6 answers)
Closed 9 years ago.
I am writing a program to compare a few characters with a Char Array and return the index of the array. Is there any possible way to compare ignore case?
For example below:
String in = "I AM A HAPPY BOY";
char[] cha = new char[] {a,c,e,g,i,k,h,m,o,q,s,u,w,y};
char testChar = in.substring(4,5).charAt(0);
for(int a = 0; a<char.length; a++){
if(cha[a] == testChar)
return a+1;
}
I am unable to get the index as it will always point to 0. Is there anyway to ignore case here? Appreciate some advise.
Use Character.toLowerCase on both characters:
if (Character.toLowerCase(cha[a]) == Character.toLowerCase(testChar)) {
// logic here
}
As a side note, you could get away with the first toLowerCase if all the characters in your array are already lower case, or even use toLowerCase on the initial string and avoid both.
You can use Character.toLowerCase(char):
if (Character.toLowerCase(cha[a]) == Character.toLowerCase(testChar)) {
return a+1;
}
use Character.ToLowerCase(char c) before testing for equality.
in=in.toLowerCase();
However the most efficient way to convert chars between cases is to flip the 6th bit (ASCII values differ by 32).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Printing reverse of any String without using any predefined function?
Please advise how to reverse a string without using built in methods. I want to use only string class, please advise let say there is a string "john is a boy" and print "yob a si nhoj".
This method will return the string backwards. all you have to do is iterate through the string backwards and add it to another string.
you do this using a for loop, but first check if the string has a greater lenght than 0.
Java Strings have a method "charAt(index)" which return a single character on the position of the string, where position 0 is the first character. so if you would like to reverse "Boy" you would start on letter 2, then 1, and then 0, and add them all together into a new String, resulting in "yoB".
public static String reverseString(String inString) {
String resultString = "";//This is the resulting string, it is empty but we will add things in the next for loop
if(inString.length()>0) {//Check the string for a lenght greater than 0
//here we set a number to the strings lenght-1 because we start counting at 0
//and go down to 0 and add the character at that position in the original string to the resulting one
for(int stringCharIndex=inString.length()-1;stringCharIndex>=0;stringCharIndex--) {
resultString+=inString.charAt(stringCharIndex);
}
}
//finaly return the resulting string.
return resultString;
}
You could iterate through all the characters in your string and prepend them to a StringBuffer using the insert(0, char) method. Then at the end of the iteration, your StringBuffer will be the reversed string.
In Java,
I need to read lines of text from a file and then reverse each line, writing the reversed version into another file. I know how to read from one file and write to another. What I don't know how to do is manipulate the text so that "This is line 1" would be written into the second file as "1 enil si sihT"
since these are homeworks you are probably interested in your own implementation of reverse method.
The naive version visits the string backwards (from the last index to the index 0) while copying it in a StringBuilder:
public String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
for example the String "hello":
H e l l o
0 1 2 3 4 // indexes for charAt()
the method start by the index 4 ('o') then the index 3 ('l') ... until 0 ('H').
StringBuilder buffer = new StringBuilder(theString);
return buffer.reverse().toString();
If this is homework, it would be better for you to understand how are data stored into the string it self.
A string may be represented as an array of characters
String line = // read line ....;
char [] data = line.toCharArray();
To reverse an array you have to swap the positions of the elements. The first in the last, the last in the first and so on.
int l = data.length;
char temp;
temp = data[0]; // put the first element in "temp" to avoid losing it.
data[0] = data[l - 1]; // put the last value in the first;
data[l - 1] = temp; // and the first in the last.
Continue with the rest of the elements ( hint use a loop ) in the array and then create a new String with the result:
String modifiedString = new String( data ); // where data is the reversed array.
If is not ( and you really just need to have the work done ) use:
StringBuilder.reverse()
Good luck.
String reversed = new StringBuilder(textLine).reverse().toString();
The provided answers all suggest using an already existing method, which is sound advice and usually more effective than writing your own.
Depending on the assignment, however, your teacher might expect you to write a method of your own. If that is the case, try using a for loop to walk through the string character by character, only instead of counting from zero and up, start counting from the last character index and down to zero, consecutively building the reversed string.
While we're feeding horrible, finished answers to the poor student, we might as well whet his appetite for the bizarre. If strings were guaranteed to be reasonably short and CPU time was no object, this is what I'd code:
public static String reverse(String str) {
if (str.length() == 0) return "";
else return reverse(str.substring(1)) + str.charAt(0);
}
(OK, I admit it: my current favorite language is Clojure, a Lisp!)
BONUS HOMEWORK: Figure out if, how and why this works!
java.lang.StringBuffer has a reverse method.