0
Outputs time limit exceeded. I am trying to reverse a string without using string functions.Help me out.
import java.util.*; public class Program { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter the string"); char s[]=in.next().toCharArray(); char ch; int l=0,i; boolean isNo= (s[l]!=0); for(l=0;isNo=true; l++); for(i=0;i<l/2;i++){ ch=s[i]; s[i]=s[l-i-1]; s[l-i-1]=ch; } System.out.print(s); }}
8 Respuestas
+ 2
Hrithik Muskan
I have updated the code to calculate the string length without using 'length' attribute. It uses a for each loop to count the char array elements.
Hth, cmiiw
+ 3
I guess the culprit was this "for(l=0;isNo=true;l++);" here you used assignment operator rather than checking for equality, if you want to use this approach you should rather check s[l]!=0 in each iteration. It is easier to use s.length I think : )
(Edit)
Code updated
import java.util.*;
public class Program {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("Enter the string:");
char s[]=in.nextLine().toCharArray();
char ch;
int i, l = 0;
for(char c : s)
l++; // count char array length
for(i = 0; i < l / 2; i++) {
ch = s[i];
s[i] = s[l-i-1];
s[l-i-1] = ch;
}
System.out.print(s);
}
}
Hth, cmiiw
+ 3
Hrithik Muskan
It means "for each (character c) in (char array s) increment the value of 'l' variable". I found out that the char array doesn't use null terminator as it is in C/C++, and I guess that was a workaround : )
P.S. Please don't call me Sir, I am a student of SoloLearn, just like you : )
Hth, cmiiw
+ 3
Hrithik Muskan
You're very welcome, I am glad if it helps : )
+ 2
It happens sometimes, you just have to keep trying.
it'll definitely work
+ 1
Ipang Sir,I was supposed to do this without using string functions, I mentioned it in the question there.
+ 1
Ipang Sir, help me with the for loop condition (char c:s), what does it mean?
+ 1
Ipang Sir,thanks a lot for helping me with my concepts.
And please don't mind calling you Sir, at least you are teaching me smthng and helping me out😁