繁体   English   中英

如何在Java中打印字符串的中间三个字符?

[英]How to print the middle three characters of a String in Java?

我是编程和处理 Java 字符串分配的新手。 问题说:

  1. 声明一个名为 middle3 的 String 类型变量(将你的声明和其他声明放在程序顶部附近),并使用赋值语句和 substring 方法为 middle3 分配由短语中间三个字符(中间的字符)组成的子串索引以及左边的字符和右边的字符)。 添加一个 println 语句来打印结果。 保存、编译并运行以测试您到目前为止所做的工作。

这是我所做的:

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)-1str.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.

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