Java Logic programming. remove white space from string, substring -Given a string of odd length, return the string length 3 from its middle, so "Candy" yields "and". The string length will be at least 3.
middleThree("Candy") → "and"
middleThree("and") → "and"
middleThree("solving") → "lvi"
Solution : (to print string length 3 from its middle)
class techietouch {
public void middleThree(String str) {
String newsub;
str=str.replaceAll("\\s","");
int length = str.length();
if (length == 3)
System.out.println(str);
int remo= (length /2)-1;
newsub =str.substring(remo,remo+3);
System.out.println(newsub);
}
public static void main(String args[]){
techietouch t = new techietouch();
t.middleThree("xyxyxabcxyxyx");
t.middleThree("candy");
}
}
Explanation:
String length will be odd so String of length 5 should remove 1-char at both end to obtain
the middle 3 char in a string, Likewise 7(string of length 7 ) should remove 2-char at both end
9 should remove 3-char
11 should remove 4-char
13 should remove 5-char
15 should remove 6-char and so on ....
The statement "" int remo= (length /2)-1; "" -> (13/2)-1 = 5 , Will return value 5. So the string of length 3 from its middle can be obtained.
ex : xyxyxabcxyxyx - > abc
***** Like us in FB & get more updates ... Like
Related Post :
Java Logic programming.
0 comments:
Post a Comment