Computer Science, asked by agnivmitra11, 7 months ago

Write a program to accept a string in upper case and display the longest word and the length of the longest word present in the string.​

Answers

Answered by Anonymous
2

Java:

import java.util.*;

class LongestWordLength

{

static int LongestWordLength(String str)

{

int n = str.length();

int res = 0, curr_len = 0;

for (int i = 0; i < n; i++)

{

// If current character is not

// end of current word.

if (str.charAt(i) != ' ')

curr_len++;

// If end of word is found

else

{

res = Math.max(res, curr_len);

curr_len = 0;

}

}

// We do max one more time to consider

// last word as there won't be any space

// after last word.

return Math.max(res, curr_len);

}

public static void main(String[] args)

{

String s = "I feel proud to answer your question";

System.out.println(LongestWordLength(s));

}

}

python:

def LongestWordLength(str):

n = len(str)

res = 0; curr_len = 0

for i in range(0, n):

# If current character is

# not end of current word.

if (str[i] != ' '):

curr_len += 1

# If end of word is found

else:

res = max(res, curr_len)

curr_len = 0

# We do max one more time to consider

# last word as there won't be any space

# after last word.

return max(res, curr_len)

# Driver Code

s = "I feel proud to answer your question"

print(LongestWordLength(s))

# This code is contribute by Smitha Dinesh Semwal.

Similar questions