简体   繁体   中英

Printing first half of a string in java

I am trying to take the first half of a string and only print the first half. For example, if the string is "Tomorrow", the print would be "Tomo"

I have seen people say to use string.length() / 2 , but I tried this and it only prints the letter after the middle. In the example that would be "r". Just looking for a push in the right direction.

我相信您想使用substring时尝试使用charAt进行打印:

System.out.println(yourString.substring(0, yourString.length() / 2));

您可以使用substring

str.substring(0, str.length() / 2);

Let me explain why your way prints 'r'.

The total length of word 'Tomorrow' is 8.

So half is 8/2 which is 4.

Now understand this, index always start from zero. So the

Zeroth letter is 'T'

First 'o'

Second 'm'

Third 'o'

Fourth 'r'

That is why it prints 'r' To print first half of string you need to give starting and ending index which you can do by using substring method of String class

You can use like this :-

 str.substring(0, str.length() / 2);

Hope it makes crystal clear.

int len=yourString.length()/2;
String halfString=yourString.substring(0,len);
sysout(halfString);

Try above, just made it quite simple and modular for better understanding.

Java's String class has a method called 'substring'

String s = "Tomorrow";
System.out.println(s.substring(0, 4)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM