String length() comparison is not working properly - java

public class LongWord {
public static void main(String args[]) {
String text = "my brother is taller than me#1233334. I always a short man,but smart than him";
// Find the longest word in the String
String[] words = text.split("\\s");
String longestWord = "";
for (int i = 1; i < words.length; i++) {
int firstLen = words[i - 1].length();
int secondLen = words[i].length();
if (firstLen <= secondLen) {
longestWord = words[i];
}
}
System.out
.println("===================================================\nLongest Word:::: \n");
System.out.println(longestWord);
}
}
// This is the sample program to find the longest word in the statement. so the output should be "me#1233334" word. but I am getting "man,but" word as output. can anyone please help me what is wrong with program.

Your method doesn't find the largest string in an array of strings. It finds the last string in an array of strings which is larger than the string directly before it.
Your comparison (firstLen <= secondLen) doesn't compare either of the strings to the current longest string. Your main loop should be:
String longestWord = words[0];
for(String word : words) {
if(word.length() > longestWord.length()){
longestWord = word;
}
}
You can also use for(int i = 0; i < words.length(); i++) and use words[i] instead of (String word : words) and word

The logic for deciding the longest word is wrong.
You are comparing a "word" (in this context, word just means something separated by a white space) with the previous word, and if it is longer, that is now the longest.
man,but is selected because it is simply longer than its previous word (short). Note that nothing after man,but is selected because no words after that are longer than their previous word

You're doing it wrong. You aren't comparing if the secondLen is bigger than longestWord, it should actually be:
longestWord = words[0];
for (int i = 1; i < words.length; i++) {
int longestLen = longestWord.length();
int secondLen = words[i].length();
if (longestLen <= secondLen) {
longestWord = words[i];
}
}

Related

Turning the Nth (input from user) number into Uppercase and the rest will be in Lowercase

I will ask this again. I have this problem which is to create a program that would read a string input from the user (sentence or word). And the Nth number (from the user) will turn into upper case and the rest will be in lowercase.
Example:
string = "good morning everyone"
n = 2
Output = gOod mOrning eVeryone
for (int x = 0; x < s.length(); x++)
if (x == n-1){
temp+=(""+s.charAt(x)).toUpperCase();
}else{
temp+=(""+s.charAt(x)).toLowerCase();
}
s=temp;
System.out.println(s);
}
Output: gOod morning everyone
I know what you want to happen - but you didn't phrase your question very well. The only part your missing is iterating through every word in the sentence. If you asked "how do I apply a function on every word in a String" you likely would have gotten a better response.
This is a bit sloppy since it adds a trailing " " to the end - but you could fix that easily.
public class Test {
static String test = "This is a test.";
public static void main(String[] args) {
String[] words = test.split(" ");
String result = "";
for (String word : words) {
result += nthToUpperCase(word, 2);
result += " ";
}
System.out.println(result);
}
public static String NthToUpperCase(String s, int n) {
String temp = "";
for (int i = 0; i < s.length(); i++) {
if (i == (n-1)) {
temp+=Character.toString(s.charAt(i)).toUpperCase();
} else {
temp+=Character.toString(s.charAt(i));
}
}
return temp;
}
}
You can do this with two for loops. Iterate over each word and within the iteration iterate over each character.
toUpperCase(2, "good morning everyone");
private static void toUpperCase(int nth, String sentence) {
StringBuilder result = new StringBuilder();
for(String word : sentence.split(" ")) {
for(int i = 0; i < word.length(); i++) {
if(i > 0 && i % nth - 1 == 0) {
result.append(Character.toString(word.charAt(i)).toUpperCase());
} else {
result.append(word.charAt(i));
}
}
result.append(" ");
}
System.out.println(result);
}
gOoD mOrNiNg eVeRyOnE

How do I break a string into groups of letters with a loop in Java?

I have to write a method which breaks a string into groups. The user should give the amount of letters per group and the function should return a string that consists of the input string broken into groups. For instance, function(“HELLOYOU”, 2) would return “HE LL OY OU”.
You can use String.split() to break the string into an array of individual letters, and then combine pairs of letters, or larger groups, etc.
Here is some example code:
String[] splitInParts(String input, int size) {
String[] letters = input.split("");
String[] output = new String[letters / size];
for (int i = 0; i < output.length; i++) {
output[i] = "";
for (int j = 0; j < size; j++) {
output[i] = output[i] + letters[size * i + j];
}
}
return output;
}
There is a lot of boilerplate code missing, for example, checking that loop parameters are in range, checking strings are not null, etc. However this is a rough idea of how you could go about doing it.
You can move the characters of input String to a new String and put whitespaces on every step that equals to "size":
String function(String input, int parts) {
StringBuilder result = new StringBuilder();
int partCounter = 0;
for (int i = 0; i < input.length(); i++) {
partCounter++;
result.append(input.charAt(i));
if (partCounter == parts){
result.append(" ");
partCounter = 0;
}
}
return result.toString();
}
You could use the below code that takes in a String instance and aN int defining the number of characters to split based on. And then use the String instances split method.
public static String[] split(String input, int len){
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return null;
}
// Split the input string based on a regex pattern
return input.split(String.format("(?<=\\G.{%1$d})", len));
}
The Regular Expression that is being used here is (?<=\\G.{%1$d}) which based on len being 2 would become (?<=\\G.{2}). So this means it would split every 2 characters. So the output for a string of HELLOWORLD would be HE, LL, OW, OR, LD .
If you wanted to join those into one String separated by a space you could using the StringUtils#join method.
String joinedString = StringUtils.join(split, StringUtils.SPACE);
Which would produce "HE LL OW OR LD".
So an all in one method would be:
public static String separateNthCharacter(String input, int len) {
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return StringUtils.EMPTY;
}
String[] split = input.split(String.format("(?<=\\G.{%1$d})", len));
return StringUtils.join(split, StringUtils.SPACE);
}

LeetCode 14. longest common prefix

Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}

Java Longest word from inputs

I am a beginner-novice and I am trying to figure out why the logic for finding the largest word doesn't work.
Sometimes the output will result in the correct longest word, the first word, or more than one word.
Thanks!!
PS
I do not really care about the cases if two words of the same length, which I will work later once I figure out why this doesn't work. And once again please note I am a beginner/novice. Thanks
import java.util.Scanner;
import java.util.ArrayList;
public class Word
{
public static String word(String str)
{
int longestCount=0;
int count=0;
int newWord=0;
String theWord="";
ArrayList <String> longestWord= new ArrayList <String>();
for (int i=0; i <str.length(); i++)
{
if (str.substring(i,i+1).equals(" "))
{
if (longestCount<count)
{
longestCount=count;
theWord="";
theWord=""+str.substring(newWord,i);
newWord=i+1;
count=0;
}
}
else
{
count++;
}
}
longestWord.add(theWord);
String output="";
for (int i=0; i<longestWord.size();i++)
output+=longestWord.get(i);
return output;
}
public static void main ()
{
Scanner scan= new Scanner(System.in);
String words= scan.nextLine();
System.out.println(word(words));
}
}
You are over thinking it. Just loop through the array list once, whenever you see a longer word, store the word/or its index:
ArrayList <String> words= new ArrayList <String>();
String currLongest = words.get(0);
for (String s : words)
if(s.length() > currLongest.length())
currLongest = s;
If your words are being passed as a single String delimited by spaces, the procedure is the same. Just split them before looping:
String[] words = str.split(" ");
String currLongest = words.[0];
for (String s : words)
if(s.length() > currLongest.length())
currLongest = s;
Note that there is no need to store the longest word into a list because at any point of time, there should only be one longest word.
It'll be easier to chop up the string using split first. then you can simplify your codes to the following.
I have commented as much as I can in the code below
public static List<String> word(String str)
{
String[] choppedUpWord = str.split(" ");
int longestWordLength = 0; //we reset the longestWord if this is updated.
ArrayList <String> longestWord= new ArrayList <String>(); //the results
for(int i=0; i < choppedUpWord.length; i ++){
String theWord = choppedUpWord[i];
if(longestWordLength < theWord.length()){
//new longest word found !
longestWord.clear(); //remove the old entries
longestWord.add(theWord); // add the new word in
longestWordLength = theWord.length(); update with new length
}else if(longestWordLength == theWord.length()){
//same length as the longest word, do an appending.
longestWord.add(theWord); // add the new word in
}
}
return longestWord;
}
it returns a list instead of a String for the event when several words are the same length.
edit alternatively you can use a StringBuilder too.
public static String word(String str)
{
String[] choppedUpWord = str.split(" ");
int longestWordLength = 0; //we reset the longestWord if this is updated.
StringBuilder longestWord= new StringBuilder(); //the results
for(int i=0; i < choppedUpWord.length; i ++){
String theWord = choppedUpWord[i];
if(longestWordLength < theWord.length()){
//new longest word found !
longestWord.setLength(0); //remove the old entries
longestWord.append(theWord); // add the new word in
longestWordLength = theWord.length(); //update with new length
}else if(longestWordLength == theWord.length()){
//same length as the longest word, do an appending.
longestWord.append(" "); //add a spacing between each word (or any delimiter that you like)
longestWord.add(theWord); // add the new word in
}
}
return longestWord.toString();
}

How to get the common first substrings In two Strings

I need some help, I have two Strings and I want to get the first occurrence of common substrings.
1st String : abacdefghi
2nd String : abaciopiss
I want to get the substring
substring : abac
Thank you everyone.
It maybe isn't the best solution but my attempt would be to find the first matching characters in each string and then continue to check the following characters if they are still the same:
private static String extractFirstEqual(String a, String b) {
//Split your string into an array of characters
String[] arr = a.split("");
String[] brr = b.split("");
StringBuilder result = new StringBuilder();
//Iterate over both arrays
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < brr.length; j++) {
//Find first matching character
if (arr[i].equals( brr[j])) {
//While there are more characters in both arrays and the characters keep matching, append them
// to the result
while (arr[i].equals(brr[j]) && i < arr.length && j < brr.length) {
result.append(arr[i]);
i++;
j++;
}
return result.toString();
}
}
}
return result.toString();
}

Categories