gpt4 book ai didi

Java 循环——每个单词的第一个和最后一个字符的字符串

转载 作者:行者123 更新时间:2023-12-02 03:18:07 25 4
gpt4 key购买 nike

我目前正在圣何塞参加编程入门类(class),作为作业的一部分,我们要创建一个类,其方法要么返回包含每个单词的第一个字母的字符串,要么返回每个单词的最后一个字母的字符串。

实例变量“phrase”保存在方法中访问的短语。

规则如下:

单词之间用空格分隔,它以一封信开头,它不以空格结尾,永远不会有 2 个连续的空格,永远不会有 2 个连续的数字或标点符号。

如果短语为空,则firstLetter() 和lastLetter() 方法都必须返回空字符串。

我的问题是:这个问题有什么更有效的解决方案?我对算法很陌生,所以我希望有更成熟的方法来解决这个简单的问题。在firstLetter()和lastLetter()方法中,我会在for循环中一次检查两个字符的状态还是只检查一个字符的状态?

这是我的代码:

/**
* Processes first and last letters of words
* @author (Adrian DeRose)
*/
public class StartToFinish
{
private String phrase;

/**
* Constructs a StartToFinish object
* @param myString the phase for this object
*/
public StartToFinish(String myString)
{
this.phrase = myString;
}

/**
* Gets first letter of every word in string.
*
* @return first letter of every word in string
*/
public String firstLetters()
{
String firstLetters = "";

if (Character.isLetter(this.phrase.charAt(0)))
{
firstLetters += this.phrase.substring(0,1);
}

for (int i = 1; i < this.phrase.length(); i++)
{
char currentCharacter = this.phrase.charAt(i);
String previousCharacter = Character.toString(this.phrase.charAt(i-1));
if (Character.isLetter(currentCharacter) && previousCharacter.equals(" "))
{
String characterString = Character.toString(currentCharacter);
firstLetters += characterString;
}
}
return firstLetters;

}

/**
* Gets last letter of every word in string.
*
* @return last letter of every word in string
*/
public String lastLetters()
{
String lastLetters = "";
char lastCharacter = this.phrase.charAt(lastIndex);

if (this.phrase.length() == 0)
{
return "";
}

for (int i = 1; i < this.phrase.length(); i++)
{
char currentCharacter = this.phrase.charAt(i);
char previousCharacter = this.phrase.charAt(i-1);

if (Character.isLetter(previousCharacter) && !Character.isLetter(currentCharacter))
{
String previousCharacterString = Character.toString(previousCharacter);
lastLetters += previousCharacterString;
}
}

if (Character.isLetter(lastCharacter))
{
lastLetters += Character.toString(lastCharacter);
}

return lastLetters;
}
}

谢谢!

最佳答案

我不知道这是否是您正在寻找的内容,但这是编写相同内容的更简单的方法(抱歉我的英语)

String a="john snow winter is comming";
String[] parts = a.split(" ");
for(String word:parts){
System.out.println("first letter "+word.charAt(0)+ " last letter "+word.charAt(word.length()-1));
}

关于Java 循环——每个单词的第一个和最后一个字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020249/

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