为了账号安全,请及时绑定邮箱和手机立即绑定

获取无法识别的字符串的第二个字

获取无法识别的字符串的第二个字

猛跑小猪 2023-05-17 14:39:17
我有以下代码:String myString = "Hello world"; firstWord = myString.substring(0, myString.indexOf(" ")); secondWord= myString.substring(1, myString.indexOf(" "));第一个词正在被识别,但第二个词实际上是在切割一个字符。所以:first: HelloSecond: ello我怎样才能得到第二个字?谢谢
查看完整描述

3 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

如果你确定正好有 2 个单词,那么你可以这样做:


String myString = "Hello World";

int indexOfFirstSpace = myString.indexOf(" ");

String firstWord = myString.substring(0, indexOfFirstSpace);

String secondWord = myString.substring(indexOfFirstSpace + 1);

第二个单词是从索引到空格索引之后的子字符串,一直到字符串的末尾。


如果不确定有多少个单词,不妨使用split拆分字符串:


String[] words = myString.split(" ");

if (words.length >= 2) {

    String firstWord = words[0];

    String seconfWord = words[1];

}



查看完整回答
反对 回复 2023-05-17
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

  String myString = "Hello world";

    index(" ") will always give you the index of first occurrence of " ". So in

    String firstWord = myString.substring(0, myString.indexOf(" "));

    you start with character at 0th index and end index will be first occurrence " " which is not included.

    Hello


    Now in your second 

    String secondWord= myString.substring(1, myString.last indexOf(" "));

    you are going to start with second character.

    ello


    **If you want to get words based in space as a separator the right way is to use split**


    **Example**

    String[] words = myString.split("\\s+");

    firstWord = words[0];

    secondWord = words[1];


查看完整回答
反对 回复 2023-05-17
?
跃然一笑

TA贡献1826条经验 获得超6个赞

secondWord= myString.substring(1, myString.indexOf(" "));

为什么您的代码不起作用: 对于上面的代码行,您从字符串的“1”索引开始。索引 1 从“e”开始,因为您从 0 开始计数。因此,当您从“e”开始并停在下一个空格“”时,那将不起作用,因为它只会将单词放在“e”之间“ 和 ” ”。结果是 ello (注意。它不包括空格)

要修复此运行: secondWord= myString.substring(myString.indexOf(" "), 11);secondWord= myString.substring(6, 11);

请注意结束索引,例如,在我们的示例中来自 的 11myString.substring(6, 11)是当前计算机索引的一个加号 (+)。在本例中,字母“d”的索引为 10,但您始终将结尾索引加一。


查看完整回答
反对 回复 2023-05-17
  • 3 回答
  • 0 关注
  • 97 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信