我是新来编程和工作的Java字符串分配。这个问题说:如何在Java中打印字符串的中间三个字符?
- 声明String类型的命名中36的变量(把近程序的顶部的其他声明的声明),并使用赋值语句和thesubstring方法来分配子由中间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个字符,但如果有不是,请让我知道。预先感谢您的帮助!
不要硬代码的中间指标。想想你将如何计算任何字符串。尝试找到一个中间索引,然后中间索引+ -1是你的中间字符串,除非长度小于三。还要考虑如果字符串的长度是奇数还是偶数,你会怎么做。 –