gpt4 book ai didi

Java - 仅使用 .substring 过程在字符串中查找多个单词

转载 作者:行者123 更新时间:2023-11-29 07:48:55 25 4
gpt4 key购买 nike

我正在尝试使用空格“”来分隔用户输入的字符串中的单词。对于此示例,用户输入字符串可能是“Random Access Memory”或“Java Development Kit”。无论输入的字符串如何,空格都会分隔每个单词。除此之外,我不能使用 .split 或数组,因为这些是我迄今为止找到的最常见的解决方案。只允许使用 .substring。在我失败的尝试中,我只能获得第一个输入的单词(例如“随机”),但不能将第二个和第三个单词分开(例如“访问内存”)。我不会公布我失败的尝试,但我想问你是否可以提供分隔输入的第二个和第三个单词的代码?谢谢。

附言我知道这是用来创建首字母缩略词的,我可以做那部分,只需要识别每个子字符串。

  import javax.swing.*;
public class ThreeLetterAcronym
{
public static void main(String[] args)
{

String wordsInput, initialInput;
String first = "";
String second = "";
String third = "";

int firstWord;
int secondWord;
int wordLength;
int secondWordLength;

char c;

wordsInput = JOptionPane.showInputDialog(null, "Please enter three words");
initialInput = wordsInput;
wordLength = wordsInput.length();
firstWord = 0;
secondWord = 0;


while(firstWord < wordsInput.length())
{
if(wordsInput.charAt(firstWord) == ' ')
{
first = wordsInput.substring(0,firstWord);
second = wordsInput.substring(firstWord + 1, wordsInput.length());
//I know that this is the spot where the last two words are displayed in the output, this is
//the closest I have been to displaying anything relevant.
firstWord = wordsInput.length();

}
++firstWord;

}
JOptionPane.showMessageDialog(null, "Original phrase was: "
+ initialInput + "\nThree letter acronym is: " + first + second);
}
}

最佳答案

只是在不使用(奇怪地)使用 Spring.split 的情况下将单词分开:

String myString = "Random Access Memory";

int begin = 0;
int end;
while((end = myString.indexOf(" ", begin)) != -1) {
System.out.println(myString.substring(begin, end));
begin = end + 1;
}
System.out.println(myString.substring(begin));

关于Java - 仅使用 .substring 过程在字符串中查找多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com