In: Computer Science
Given a string of at least 3 characters as input, if the length of the string is odd return the character in the middle as a string. If the string is even return the two characters at the midpoint.
--------------------------------------------------------------
public class Class1 {
public static String midString(String str) {
//Enter code here
}
}
Please find the Updated code for the following:
Code:
public class Class1
{
//Defined a method which accepts a string and returns
a string
public static String midString(String str)
{
//Check if the string is an odd
length
if(str.length()%2==0)
{
//Then returns the two characters at the midpoint
return
str.substring(str.length()/2-1,str.length()/2+1);
}
//Else part where the string is an even length
else
{
//Then return the character in the middle
return
str.substring(str.length()/2,str.length()/2+1);
}
}
//Validating the above method
public static void main(String[] args)
{
//Defined 2 strings one is of even
and other is off odd length
String
EvenLengthString="ABCDEFGH";
String oddLengthString
="RSTUVWXYZ";
//Calling the function and then
printing out the resultant string
System.out.println(midString(EvenLengthString));
System.out.println(midString(oddLengthString));
}
}
Please check the
compiled program and its output for your reference:
Output:
(Feel free to drop me a comment, If you need any help)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...