java 在java中打印字符串的前半部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29618285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing first half of a string in java
提问by James
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. In the example that would be "r". Just looking for a push in the right direction.
我见过有人说要使用string.length() / 2
,但我试过这个,它只在中间打印字母。在这个例子中,这将是“r”。只是在正确的方向上寻找推动力。
回答by Jean-Fran?ois Savard
I believe you tried to print using charAt
while you wanted to use substring
:
我相信您charAt
在想使用时尝试使用打印substring
:
System.out.println(yourString.substring(0, yourString.length() / 2));
回答by Paramvir Singh Karwal
Let me explain why your way prints 'r'.
让我解释一下为什么你的方式打印'r'。
The total length of word 'Tomorrow' is 8.
单词“Tomorrow”的总长度为 8。
So half is 8/2 which is 4.
所以一半是 8/2,也就是 4。
Now understand this, index
always start from zero. So the
现在明白这一点, index
永远从零开始。所以
Zeroth letter is 'T'
First 'o'
Second 'm'
Third 'o'
Fourth 'r'
第零个字母是“T”
第一个'o'
第二个'm'
第三个'o'
第四个'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' 要打印字符串的前半部分,您需要提供开始和结束索引,您可以使用类的substring
方法来完成String
You can use like this :-
你可以这样使用:-
str.substring(0, str.length() / 2);
Hope it makes crystal clear.
希望它说得一清二楚。
回答by Boris
Java's String class has a method called 'substring'
Java 的 String 类有一个名为“substring”的方法
String s = "Tomorrow";
System.out.println(s.substring(0, 4));
回答by Raghvendra Gupta
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.
试试上面,只是让它变得非常简单和模块化,以便更好地理解。