开发者

string manipulation- middle 3 letters

开发者 https://www.devze.com 2023-03-09 15:15 出处:网络
After prompting for a string, I am trying to display the middle three characters of that string. How would I do that?

After prompting for a string, I am trying to display the middle three characters of that string. How would I do that?

this is开发者_运维百科 what I tried:

String middle3 = (string.length < 3) ? null : string.substring(string.length / 2 - 1), string.length / 2 + 2);


length is a method of the String class, so you need to use ():

String middle3 = (string.length() < 3) ? null : 
              string.substring(string.length() / 2 - 1, string.length() / 2 + 2);


This will work for any string that is odd, length > 3

String word = "Hello";
int midCharsStart = ((word.length() + 1) / 2) - 2;
int midCharsEnd = midCharsStart + 3;
System.out.println(word.substring(midCharsStart, midCharsEnd));
0

精彩评论

暂无评论...
验证码 换一张
取 消