I want to have a program that takes a string, splits it at a space, and prints the length of the smallest substring.
I wrote this but it just prints the length of the first string. What is my problem ?
Scanner input = new Scanner(System.in);
String inp = input.nextLine();
int counter = 0;
String[]helper =new String[inp.length()];
int minlength = Integer.MAX_VALUE;
for (int i = 0; i < inp.length(); i++)
{
if (inp.charAt(i) != ' ')
{
counter++;
continue;
}
minlength = Math.min(counter, minlength);
counter = 0;
}
System.out.println(minlength);
Use .split method to split a string by spaces.
String[] stringArray = input.split("\\s+");
Generally you could do:
String[] stringArray = input.split(" ");
But this source explains why the first option is better: How do I split a string with any whitespace chars as delimiters?
Once you have the String[] stringArray, then you can loop through it and find the smallest length.
int minlength = Integer.MAX_VALUE;
for(int i = 0; i < stringArray.length; i++){
if(stringArray[i].length() < minlength){
minlength = stringArray[i].length();
}
}
System.out.println(minlength);
Related
I am new to programming I need to reverse a string without using the library function.
I am able to reverse but as expected.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
String rev = "";
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<String> splitResult = new ArrayList<String>();
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == ' ')
list.add(i);
list.add(0, 0);
list.add(list.size(), s.length());
String[] words = new String[list.size()];
for (int j = 0; j <= words.length - 2; j++)
splitResult.add(s.substring(list.get(j), list.get(j + 1)).trim());
System.out.println(splitResult);
String[] str = new String[splitResult.size()];
str = splitResult.toArray(str);
for (int i = 0; i < str.length; i++) {
if (i == str.length - 1) {
rev = str[i] + rev;
} else {
rev = " " + str[i] + rev;
}
}
System.out.println(rev);
Expected:
Input: i am coder
output: redoc ma i
actual
input: i am coder
output: coder am i
You can just provide an empty result variable, iterate the characters of the given String by using an enhanced for-loop (also known as for-each loop) setting every character to index 0 of the result variable by just concatenating the character to the result variable like this:
public static void main(String[] args) {
// input
String s = "I am coder";
// result variable for reverse input
String reverseS = "";
// go through every single character of the input
for (char c : s.toCharArray()) {
// and concatenate it and the result variable
reverseS = c + reverseS;
}
// then print the result
System.out.println(reverseS);
}
You can of course do that in a slightly different way using a classic for-loop and the length of the input, see this example:
public static void main(String[] args) {
String s = "I am coder";
String reverseS = "";
for (int i = 0; i < s.length(); i++) {
reverseS = s.charAt(i) + reverseS;
}
System.out.println(reverseS);
}
String s = "I am coder";
String rev="";
for (int i = s.length()-1; i >=0; i--) {
rev+=s.charAt(i);
}
System.out.println(rev);
I have set the index I to the last character of the given string and the condition is set to 0(i.e the first character). Hence the loop runs from the last character to the first character. It extracts each of the characters to a given new String. Hope it helps!
You can just take another list go from last to first and display like this
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
ArrayList<Character> working = new ArrayList<Character>();
ArrayList<Character> finished = new ArrayList<Character>();
for (char ch: s.toCharArray()) {
working.add(ch);
}
for(int i = working.size() - 1 ; i>=0 ; i--){
finished.add(working.get(i));
}
for(int j = 0 ; j < finished.size() ; j++){
System.out.print(finished.get(j));
}
I'm trying to figure out how to take a array of Characters that spell out a sentence backwards (or out of order) with the words separated by spaces to distinguish them and re-order them in the correct/reversed format so instead of the character array spelling out World Good Hello it would spell out Hello Good World like this ['H','e','l','l','o',' ','G','o','o','d',' ','W','o','r','l','d']
This is more or less a shot in the dark.
In the end I would like to return it back as an array of characters.
Code:
class Main {
public static void main(String[] args) {
// World Good Hello
// reverse to: Hello Good World
char[] chrArray = new char[] {'W','o','r','l','d',' ','G','o','o','d',' ','H','e','l','l','o'};
String str = String.valueOf(chrArray);
String[] strArray = str.split(" ");
char[] result = new char[0];
for (int i = 0; i < strArray.length; i++) {
for (int h = 0; h < strArray[i].length(); h++) {
char[] temp = new char[strArray[i].charAt(h)];
temp[temp.length - 1] = ' ';
char[] both = Arrays.copyOf(result, result.length);
List<character> temp2 = System.arraycopy(temp, 0, both, result.length, temp.length);
result = temp2.toCharArray();
}
}
}
}
public static String reverseWords(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder buf = new StringBuilder(sentence.length());
for (int i = words.length - 1; i >= 0; i--) {
if (buf.length() > 0)
buf.append(' ');
buf.append(words[i]);
}
return buf.toString();
}
Use reverseWords(...).toCharArray() to get char array.
I think the following code would be enough to reverse:
String[] strArray = str.split(" ");
for(int i =strArray.length-1;i>=0;i--) {
System.out.print(strArray[i] + " ");
}
this will output : Hello Good World
The problem is
how to get the maximum repeated String in an array using only operations on the arrays in java?
so i got into this question in a test and couldn't figure it out.
lets suppose we have an array of string.
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
in str1 abbey was maximum repeated, so abbey should be returned and
in str2 abbey and caley both have same number of repetitions and hence we take maximum alphabet as the winner and is returned(caley here).
c > a
so i tried till
import java.util.*;
public class test {
static String highestRepeated(String[] str) {
int n = str.length, num = 0;
String temp;
String str2[] = new String[n / 2];
for (int k = 0;k < n; k++) { // outer comparision
for (int l = k + 1; l < n; l++) { // inner comparision
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
}
// I'm stuck here
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter how many votes");
int n = sc.nextInt();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
Str[i] = sc.nextLine();
}
String res = highestRepeated(str);
System.out.println(res + " is the winner");
}
}
so, how should i take the count of occurrence of each string with and attach it with the string itself.
All this, without using a map and any hashing but just by using arrays?
Here is a (unpolished) solution:
static String highestRepeated(String[] str) {
String[] sorted = Arrays.copyOf(str, str.length);
Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
String currentString = sorted[0];
String bestString = sorted[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1 ; i < sorted.length ; i++) {
if (currentString.equals(sorted[i])) {
currentCount++;
} else {
if (maxCount < currentCount) {
maxCount = currentCount;
bestString = currentString;
}
currentString = sorted[i];
currentCount = 1;
}
}
if (currentCount > maxCount) {
return currentString;
}
return bestString;
}
Explanation:
Sort the array from highest to lowest lexicographically. That's what Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder()); does. we sort in this order because you want the largest string if there are multiple strings with the same number of repeats.
Now we can just count the strings by looping through the array. We don't need a hash map or anything because we know that there will be no more of a string in the rest of the array when we encounter a different string.
currentString is the string that we are currently counting the number of repeats of, using currentCount. maxCount is the number of occurrence of the most repeated string - bestString - that we have currently counted.
The if statement is pretty self-explanatory: if it is the same string, count it, otherwise see if the previous string we counted (currentCount) appears more times than the current max.
At the end, I check if the last string being counted is more than max. If the last string in the array happens to be the most repeated one, bestString won't be assigned to it because bestString is only assigned when a different string is encountered.
Note that this algorithm does not handle edge cases like empty arrays or only one element arrays. I'm sure you will figure that out yourself.
another version
static String lastMostFrequent(String ... strs) {
if (strs.length == 0) return null;
Arrays.sort(strs);
String str = strs[0];
for (int longest=0, l=1, i=1; i<strs.length; i++) {
if (!strs[i-1].equals(strs[i])) { l=1; continue; }
if (++l < longest) continue;
longest = l;
str = strs[i];
}
return str;
}
change in
if (++l <= longest) continue;
for firstMostFrequent
you can't use == to check if two strings are the same.
try using this instead:
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
I'm using indexOf() to look for white spaces while trying to seperate words in a string but the index off keeps returning -1; Here's my code:-
import java.util.Scanner;
class Main {
public static void main(String[] args){
Scanner y = new Scanner(System.in);
System.out.println("Enter the String");
String s = y.nextLine();
int words = 1;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i)==' ') words++;
}
String[] a = new String[words];
int l = s.length();
for (int i = 0; i <= words; i++) {
int r = s.indexOf(" ");
a[i] = s.substring(0, r);
s = s.substring((r + 1), l);
}
for(int i = 0; i <= words; i++) {
System.out.println(a[i]);
}
}
}
The problem is that you start words at 1 and increment it for each space you find. So if there's one space, words is 2. Then you're trying to look for that many spaces - but there's only 1, so when it runs out of spaces to find, it returns -1 and you get the exception.
You can just use String.split, e.g :
String s=y.nextLine();
for(String i : s.split(" ")) {
System.out.println(i);
}
I have the following txt file that I need to split with tokens and save to an object:
1,Harry Potter,4,3,11,14,20
2,Matrix,3,1,8,12
3,Batman,3,39,9,42
Structure is: id, name, length, movieIds
Where length is reference to how many movieIds there are.
Not sure how to split movieIds separately or to set multiple values to the object as they override one another.
Scanner inputFile = new Scanner(playlistLibrary);
String str;
String[] tokens;
for (int i = 1; i < playlist.length; i ++) {
playlist[i] = new Playlist_17967352();
if (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
for (int a = 0; a < tokens.length; a ++) {
playlist[i].setId(tokens[0]);
playlist[i].setName(tokens[1]);
playlist[i].setLength(tokens[2]);
if (tokens.length > 3) {
int length = Integer.parseInt(playlist[i].getLength());
String movieIds;
for (int b = 0, c = 3 ; b < length; b++, c++) {
movieIds = tokens[c];
playlist[i].setMovies(movieIds);
}
}
} // end for tokens.length
System.out.println(playlist[i].getMovies());
Code output:
20
12
42
What I need is:
3,11,14,20
1,8,12
39,9,42
You can just do one split. You know that the first movie id is at tokens[3], so you only need one counter in your loop and then add 3 when indexing tokens.