Can we reverse a string by using maths logic without using for loop logic(starting with len-1) or built-in functions
-
Is a while loop allowed? Or are any loop constructs forbidden? Is recursion allowed?Moritz Schmidt– Moritz Schmidt2019-07-29 17:12:18 +00:00Commented Jul 29, 2019 at 17:12
-
1loop allowed but not that condition that we start from end of string and print charAt that, like in numbers we use that trick find modulous and divide ,can we do it with strings???Simran Nagdeo– Simran Nagdeo2019-07-29 17:15:15 +00:00Commented Jul 29, 2019 at 17:15
-
You should print or get a new string at the end ?azro– azro2019-07-29 17:16:11 +00:00Commented Jul 29, 2019 at 17:16
-
Simran, you start a whileloop looping through the string char by char. YOU Check to see if the next char is null. If it's null, exit the loop. Else, create or append to an array with the current char (in the correct order so the string is reversed (that's just regular business logic)).JD333– JD3332019-07-29 17:25:31 +00:00Commented Jul 29, 2019 at 17:25
-
not a duplicate? reversing a string?Artanis– Artanis2019-07-29 17:36:18 +00:00Commented Jul 29, 2019 at 17:36
|
Show 2 more comments
3 Answers
If recursion allowed:
public class Test {
static void reverse(int pos, String str){
if(pos==str.length()) return;
reverse(pos+1, str);
System.out.print(str.charAt(pos));
}
public static void main(String[] args) {
String str = "what ever";
reverse(0, str); // here we start from position zero.
System.out.println("");
}
}
Comments
You can do this with strings with fixed size character, but you have to implement your custom bignumber which supports at least radix 256 (for 8 bit encoding, 65536 for 16 bit, etc).
Then you will be able to get modulo 256, divide and thus get reversed string as you do with numbers.
But, this approach will give you horrible performance, so use it just for fun.
Comments
You can use apache StringUtils lib and use the reverse method as below.
StringUtils.reverse("abc");
It will return "cba".
1 Comment
Nexevis
"Without using built-in functions", I don't think using an external library meets the requirements.