How can I find the longest word in a string?
You can use max
on the splitted string with key
as len
:
max_word = max(string.split(), key=len)
You can also correct your code to:
string = input("Please enter a string ")
max_word = ''
for word in string.split():
if len(word) > len(max_word):
max_word = word
print(max_word)
Program to find the longest word in a string
Using goto
is highly discouraged. You should convert your code to use a loop.
The main problem in your code is you do not stop the scan when you reach the end of the string.
Here is a modified version:
#include <stdio.h>
int main() {
char string[100] = "Hello Kurnool";
int i, letters, longest = 0, longest_pos = 0;
for (i = 0; string[i] != '\0'; i++) {
for (letters = 0; string[i] != '\0' && string[i] != ' '; i++) {
letters++;
}
if (letters > longest) {
longest = letters;
longest_pos = i - longest;
}
}
printf("longest word: %d letters, '%.*s'\n",
longest, longest, string + longest_pos);
return 0;
}
Note that the implementation can be simplified into a single loop:
#include <stdio.h>
int main() {
char string[100] = "Hello Kurnool";
int i, start = 0, longest = 0, longest_pos = 0;
for (i = 0; string[i] != '\0'; i++) {
if (string[i] == ' ') {
start = i + 1;
} else {
if (i - start > longest) {
longest = i - start;
longest_pos = start;
}
}
}
printf("longest word: %d letters, '%.*s'\n",
longest, longest, string + longest_pos);
return 0;
}
Return the longest word in a string
Loop through the words and If the current word have more length than previous word,then make longest word as current word.So at the end you will get longest word.
public class Longest {
public static String longWord(String[] words) {
//assume initially the longest word is an empty String
String longestWord = "";
//loop through each word
for (String word: words) {
//check if the each items length with previous largest length
if (word.length() > longestWord.length()) {
//make longest word as current if it matches the condition
longestWord = word;
}
}
//return the longest word,if word array is empty it return empty String
return longestWord;
}
}
Or Use the Array sort method to find the largest element as follows
public class Longest {
public static String longWord(String[] word) {
//sort the array based on the length,So that
// largest element will be at the end of the array
Arrays.sort(word, Comparator.comparing(String::length));
//return the last element
return word[word.length-1];
}
}
Julia: How to find the longest word in a given string?
You can use regex too. It only needs a slight change from @Bogumil's answer:
julia> function LongestWord2(sen::AbstractString)
words = matchall(r"\w+", sen)
words[findmax(length.(words))[2]]
end
LongestWord2 (generic function with 1 method)
julia> LongestWord2("Hello, how are you? nested, punctuation?")
"punctuation"
This way you get rid of the punctuations and get the raw word back.
To consolidate the comments here's some further explanation:
matchall()
takes a regex, in this case r"\w+"
which matches word like substrings, so letters, numbers and lowercases and returns an array of strings that match the regex.
length.()
is using the combination of the length
function and .
which broadcasts the operation across all elements of the array. So we're counting the length of each array element (word).
Findmax()
returns a tuple of length 2 where the 2 argument gives us the index of the maximum element. I use this to subset the words
array and return the longest word.
How do I find the longest words in a string?
Then you have to use a collection of these longestWords
, e.g.
ArrayList<String> longestWords = new ArrayList<String>();
int longestWordLength = 0;
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWordLength) { // longer
longestWordLength = sentence[i].length();
longestWords.clear();
longestWords.add(sentence[i]);
}
else if (sentence[i].length() == longestWordLength) { // same length
longestWords.add(sentence[i]);
}
}
for (int i = 0; i < longestWords.size(); ++i)
System.out.println(longestWords.get(i));
How to find the longest word in a string without using split method
I've split this problem into two parts:
Use
find
to create the list of words.Find the longest word in the list.
def plus_long(ch):
letters = "abcdefghijklmnopqrstuvwxyz"
words = ['']
for v in ch:
if letters.find(v.lower()) != -1: # Use find to check if the character is part of the alphabet
words[-1] += v # If so, add that character to the last string in the list
else:
words.append('') # Else, start a new string
result = "" # Check which string is the longest
for word in words:
if len(word) > len(result):
result = word
return result
Test:
>>> plus_long("Hello!!!!!!!!!!! How are you? I am exhausted.")
Output:
'exhausted'
I see that the other answers don't put punctuation into account, so that using their functions, the result would be 'Hello!!!!!!!!!!!'
.
Finding the longest word ArrayList /Java
The fact is that you can't tell what the biggest word until you have iterated the whole list.
So iterate on the list
- if word is bigger than previous largest size : clear list and save word
- if word has same size as largest size : save word
- if word is smaller : nothing
List<String> wordsList = Arrays.asList(
"december", "california", "cat",
"implementation", "incremntation");
int maxLength = Integer.MIN_VALUE;
List<String> largestStrings = new ArrayList<>();
for (String s : wordsList) {
if (s.length() > maxLength) {
maxLength = s.length();
largestStrings.clear();
largestStrings.add(s);
} else if (s.length() == maxLength) {
largestStrings.add(s);
}
}
if (largestStrings.size() > 1) {
System.out.println("More than one longest word");
System.out.println(largestStrings);
} else {
System.out.println(largestStrings.get(0) + " is the longest word");
}
Gives
More than one longest word
[implementation, incrementation]
Related Topics
Converting Exponential Value in Java to a Number Format
The Import Org.Junit Cannot Be Resolved
Eclipse No Tests Found Using Junit 5 Caused by Noclassdeffounderror for Launcherfactory
Java.Lang.Noclassdeffounderror: Com/Fasterxml/Jackson/Databind/Exc/Invaliddefinitionexception
Split Comma Separated Values in Java, Int and String
Spring Security Configuration Filter Any Requests Except a Specific Endpoint
How to Handle Errors in Spring-Webflux
Get the Nearest Date to Specific from the List of Dates
How to Find Max Duplicate Number Count in Given Array Using for Loop
In Java, How to Combine Two Json Arrays of Objects
Javax.Net.Ssl.Sslexception: Certificate Doesn't Match Any of the Subject Alternative Names
Getting Data from Incoming Json in a Java Servlet
Automatically Size Jpanel Inside Jframe
Handling Static Variables in Multithreaded Java Program
Error While Running Allure Command Line Generate Command
Regular Expression to Validate Username