简体   繁体   English

在Java中打印字符串的前半部分

[英]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" 例如,如果字符串是“ Tomorrow”,则打印内容将是“ Tomo”

I have seen people say to use string.length() / 2 , but I tried this and it only prints the letter after the middle. 我见过有人说要使用string.length() / 2 ,但是我尝试了这个,它只在中间的后面打印字母。 In the example that would be "r". 在示例中将为“ 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'. 让我解释一下为什么您的方式显示“ r”。

The total length of word 'Tomorrow' is 8. “明天”一词的总长度为8。

So half is 8/2 which is 4. 所以一半是8/2,即4。

Now understand this, index always start from zero. 现在了解这一点, index总是从零开始。 So the 所以

Zeroth letter is 'T' 零字母是'T'

First 'o' 第一个“ o”

Second 'm' 第二个“ m”

Third 'o' 第三“ o”

Fourth 'r' 第四“ 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 这就是为什么要打印'r'的原因。要打印字符串的前半部分,您需要提供开始和结束索引,您可以使用String类的substring方法执行此操作

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' Java的String类具有一种称为“ substring”的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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