[英]How to print the middle three characters of a String in Java?
我是编程和处理 Java 字符串分配的新手。 问题说:
这是我所做的:
String phrase = new String ("This is a String test.");
String middle3 = new String ("tri"); //I want to print the middle 3 characters in "phrase" which I think is "tri".
middle3 = phrase.substring (9, 11); // this only prints out 1 letter instead of 3
System.out.println ("middle3: " + middle3);
这是我的输出:
Original phrase: This is a String test.
Length of the phrase: 18 characters
middle3: S
我也认为字符串“短语”中有 18 个字符,但如果没有,请告诉我。 在此先感谢您的帮助!
考虑如何在不硬编码substring()
方法的边界的情况下检索中间 3 个字符。 您可以在这方面使用length()
方法。 例如,奇数长度字符串的中间字符将始终位于索引str.length()/2
,而偶数长度字符串的两个中间字符将始终位于索引str.length()/2
和(str.length()/2) - 1
。 所以中间三个字符的定义取决于你。 但为了我们的缘故,我们只会在索引(str.length()/2)-1
、 str.length()/2
和(str.length()/2)+1
处制作 3 个中间字符。 有了这些信息,你可以修改你之前的这行代码,
middle3 = phrase.substring (9, 11);
到
middle3 = phrase.substring (phrase.length()/2 - 1, phrase.length()/2 + 2);
至于为什么你之前的原始代码行只返回一个字母,这与substring
方法的参数有关。 第一个参数是包含的,但第二个参数不是。 因此,您只检索了 9 到 10 个字符。
This is a String test.
^^^
9,10,11 (11 is not included)
我指向的三个字符分别位于索引 9、10 和 11。 您只检索了字符 ' ' 和 'S',它们合起来就是“S”。 这解释了之前的单字母输出。
首先, phrase
有 22 个字符。
"This is a String test."
^^^^^^^^^^^^^^^^^^^^^^ --> 22
请注意,空格 ( ) 计入字符数。 此外,
String
有一个方法length()
可以给你这个数字。
String phrase = "This is a String test.";
int phraseLength = phrase.length(); //22
从那里,我们可以通过处理值phraseLength/2
来获得中间的三个字符。 中间的三个字符会在中间位置之前开始一个,然后停止一个。 但是,因为string(int, int) 方法将结束索引设为exclusive
,所以我们应该将其加一。
String phrase = "This is a String test.";
int phraseLength = phrase.length(); //22
String middle3 = phrase.substring(phraseLength/2 - 1, phraseLength/2 + 2); // will have the middle 3 chars.
如果phrase
的长度是奇数,这将返回中间 3 个字符。 如果phrase
的长度是偶数(就像这里一样),这将返回左中 3 个字符。 (例如,在1,2,3,4
,我使用 left-middle 表示2
和 right-middle 表示3
)。
另一个注意事项是,编写new String("asdf")
既不必要又糟糕。 只需使用字符串文字即可。
String phrase = new String ("This is a String test."); //Bad
String phrase = "This is a String test."; //Good
您在字符串中的开始索引和结束索引中有错误,这是正确的代码:
String phrase = new String("This is a String test.");
String middle3 = phrase.substring(11, 14);
System.out.println("middle3: " + middle3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.