Actuellement, je suis capable de comprendre comment afficher la longueur de mot la plus longue. Cependant, existe-t-il un moyen d'utiliser des boucles pour déterminer le mot le plus long et aussi l'imprimer?
public static void longestWordCalculator(String rawText)
{
int lengthCounter = 0;
int finalCounter = 0;
int textLength = rawText.length();
for (int i = 0; i < textLength ; i++)
{
String indexValue = Character.toString(rawText.charAt(i));
if(!" ".equals(indexValue))
{
lengthCounter++;
}
else
{
finalCounter = Math.max(finalCounter, lengthCounter);
lengthCounter = 0;
}
}
System.out.println("Final Value: " + Math.max(finalCounter, lengthCounter));
}
7 Réponses :
Peut utiliser split () pour diviser la chaîne en un tableau de chaînes, puis parcourir chaque élément pour vérifier la longueur du mot. Dans cet exemple, nous supposons qu'il n'y a pas de caractères spéciaux et que les mots sont séparés par des espaces.
Cette fonction trouvera le premier mot le plus long, c'est-à-dire que s'il y a une égalité, elle affichera le premier mot avec la longueur la plus longue . Dans l'exemple ci-dessous, vous pouvez voir que look et plus long ont le même nombre de caractères, mais il ne produira que look . P >
public static void longestWordCalculator(String rawText)
{
int nextSpaceIndex = rawText.indexOf(" ") + 1;
String longestWord = "";
do {
String word = rawText.substring(0, nextSpaceIndex);
rawText = rawText.substring(nextSpaceIndex); // trim string
if (word.length() > longestWord.length()) {
longestWord = word;
}
int tempNextIndex = rawText.indexOf(" ") + 1;
nextSpaceIndex = tempNextIndex == 0 ? rawText.length() : tempNextIndex;
} while (rawText.length() > 0);
System.out.println("Longest word: " + longestWord);
System.out.println("With length of: " + longestWord.length());
}
Utilisation:
longestWordCalculator ("Bonjour, je cherche le mot le plus long");
Sorties
Mot le plus long: recherche
D'une longueur de: 7
EDIT:
Sans utiliser de tableaux:
public static void longestWordCalculator(String rawText)
{
int textLength = rawText.length();
String longestWord = "";
String[] words = rawText.split("\\s");
for (int i = 0; i < words.length; i++)
{
if (words[i].length() > longestWord.length()) {
longestWord = words[i];
}
}
System.out.println("Longest word: " + longestWord);
System.out.println("With length of: " + longestWord.length());
}
l'affectation demande de ne pas utiliser de tableaux ... est-ce possible? J'ai pu le faire facilement avec des tableaux, mais sans se gratter la tête
Ouais, j'en code un en utilisant juste une boucle while et aucun tableau :)
OK, veuillez vérifier la modification. Si les gens vous ont aidé, n'oubliez pas de voter :)
Divisez le texte par espace et trouvez le mot le plus long. Essayez ce code.
public class Test {
public static void longestWordCalculator(String rawText) {
String[] words = rawText.trim().replaceAll(" +", " ").split(" ");
int foundIndex = -1;
int maxLenght = 0;
String foundWord = "";
for (int i = 0; i < words.length; i++) {
if (words[i].length() > maxLenght) {
maxLenght = words[i].length();
foundWord = words[i];
foundIndex = i;
}
}
System.out.println(String.format("Longest word is [Word=%s, WordLength=%s, WordIndex=%s]", foundWord, maxLenght, foundIndex));
}
public static void main(String args[]) {
longestWordCalculator("It looks good");
}
}
Entrée: "Ça a l'air bien"
Sortie: Le mot le plus long est [Word = looks, WordLength = 5, WordIndex = 1] p >
l'affectation demande de ne pas utiliser de tableaux ... est-ce possible? J'ai pu le faire facilement avec des tableaux, mais sans se gratter la tête
J'ai ajouté un autre code. Il conserve votre implémentation, sans utiliser de tableau.
Utilisez un modèle et un Matcher et une boucle while . Quelque chose comme,
public static void longestWordCalculator(String rawText) {
Pattern p = Pattern.compile("(\\S+)\\b");
Matcher m = p.matcher(rawText);
String found = null;
while (m.find()) {
String s = m.group(1);
if (found == null || s.length() > found.length()) {
found = s;
}
}
if (found == null) {
System.out.println("No words found");
} else {
System.out.printf("The longest word in \"%s\" is %s which is %d characters.%n",
rawText, found, found.length());
}
}
Les deux réponses publiées sont bonnes et je les utiliserais, mais si vous vouliez conserver votre implémentation actuelle et éviter les tableaux, etc., vous pouvez enregistrer l'emplacement du début de la chaîne la plus longue actuelle lorsque vous enregistrez la nouvelle longueur la plus longue avec longestIndex = i - lengthCounter . À la fin, imprimez la sous-chaîne dans rawText de longestIndex à longestIndex + finalCounter .
Modifier - essayez quelque chose comme ça p >
int lengthCounter = 0;
int finalCounter = 0;
int textLength = rawText.length();
int longestIndex = 0;
for (int i = 0; i < textLength ; i++)
{
String indexValue = Character.toString(rawText.charAt(i));
if(!" ".equals(indexValue))
{
lengthCounter++;
}
else
{
if (lengthCounter > finalCounter) {
longestIndex = i - lengthCounter;
finalCounter = lengthCounter;
}
lengthCounter = 0;
}
}
System.out.println("Final Value: " + finalCounter);
System.out.println("Longest Word: " + rawText.substring(longestIndex, longestIndex + finalCounter));
à quoi cela ressemblerait-il dans ma mise en œuvre?
@ jimmyjohn123 J'ai édité ma réponse avec une implémentation. Je ne l'ai pas testé mais ça devrait être quelque chose du genre
Voici une solution sans fractionnement:
Longest word is: amigo Longest word is: quiero Longest word is: bblablabla No solution finded!
Sortie:
public class LongestWord {
public static void longestWordCalculator(String rawText)
{
int lastSeparator = -1;
int maxLength = 0;
int solPosition = 0;
int textLength = rawText.length();
for (int i = 0; i < textLength ; i++)
{
//here you may check for other separators
if (rawText.charAt(i) == ' ') {
lastSeparator = i;
}
//assuming no separator is part of a word
else {
if (i - lastSeparator > maxLength) {
maxLength = i - lastSeparator;
solPosition = lastSeparator;
}
}
}
if (maxLength > 0) {
String solution = rawText.substring(solPosition+1, solPosition+maxLength+1);
System.out.println("Longest word is: " + solution);
}
else {
System.out.println("No solution finded!");
}
}
public static void main (String args[]) {
longestWordCalculator("la casa de mi amigo");
longestWordCalculator("quiero agua");
longestWordCalculator("bblablabla");
longestWordCalculator("");
}
}
Je garde votre code, je n'utilise pas de tableau. Voici le code mis à jour:
public class Test {
public static void longestWordCalculator(String rawText) {
int lengthCounter = 0;
int finalCounter = 0;
int textLength = rawText.length();
StringBuffer processingWord = new StringBuffer();
String foundWord = null;
for (int i = 0; i < textLength; i++) {
String indexValue = Character.toString(rawText.charAt(i));
if (!" ".equals(indexValue)) {
processingWord.append(rawText.charAt(i));
lengthCounter++;
} else {
if (finalCounter < lengthCounter) {
finalCounter = lengthCounter;
foundWord = processingWord.toString();
processingWord = new StringBuffer();
}
lengthCounter = 0;
}
}
System.out.println("Final Value: " + finalCounter + ", Word: " + foundWord);
}
public static void main(String args[]) {
longestWordCalculator("It looks good");
}
}
J'espère que cela pourra vous aider.
Cette solution ici est astucieuse, et elle affichera en fait tous les mots avec la longueur la plus longue, au lieu d'un seul.
public class Main {
public static void main(String[] args) {
String string = "one two three four five six seven eight nine";
String currentWord = "";
String largestWords = "";
int longestLength = 0;
for (int i = 0; i < string.length(); i++) {
char iteratedLetter = string.charAt(i);
if (iteratedLetter == ' ') { // previous word just ended.
if (currentWord.length() > longestLength) {
largestWords = "";
longestLength = currentWord.length();
}
else if (currentWord.length() == longestLength) {
largestWords += currentWord + " ";
}
currentWord = "";
}
else {
currentWord += iteratedLetter;
}
}
System.out.println("Largest words: " + largestWords);
}
}
J'encourage à comprendre le code, car vous l'avez dit un devoir.