Java - Mix up letters - java

Can someone give me an example of how to split Strings before you scramble the letters
I can scramble the words but it changes the length of the words too
Example:
input : Hello my name is Jon
output: e imanoJs my nlolHe
But it should be like this
input : Hello my name is Jon
output: Hlelo my nmae is Jon
so the first and last letter should stay in place
here is my code so far
public class MixUp{
public static void main(String[] args){
String cards="Hello my Name is Jon, nice to meet you";
System.out.println("Input String = " + cards);
cards = shuffle(cards);
System.out.println("Shuffled String = " + cards);
}
static String shuffle(String cards){
if (cards.length()<=1)
return cards;
int split=cards.length()/2;
String temp1=shuffle(cards.substring(0,split));
String temp2=shuffle(cards.substring(split));
if (Math.random() > 0.5)
return temp1 + temp2;
else
return temp2 + temp1;
}
}

Notes
Use Collections.shuffle() in combination with List.subList() so that the first and last letters are not moved.
Convert to and from primitive array so that Collections.shuffle() can be used
Code
private static String shuffle(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder builder = new StringBuilder();
for (String word : words) {
List<Character> letters = new ArrayList<Character>();
for (char letter : word.toCharArray()) {
letters.add(letter);
}
if (letters.size() > 2) {
Collections.shuffle(letters.subList(1, letters.size() - 1));
}
for (char letter : letters) {
builder.append(letter);
}
builder.append(" ");
}
return builder.toString();
}

inputString.split(" ") will split on spaces and return an array of Strings. Create a new array, iterate through the first split array and shuffle each string and add the shuffled string to the new array.
String cards="Hello my Name is Jon, nice to meet you";
System.out.println("Input String = " + cards);
String[] splt = cards.split(" ");
String[] shuffled = new String[splt.length];
for (int iter = 0; iter < splt.length; iter ++){
shuffled[iter] = shuffle(splt[iter]);
}
// Now join the array
EDIT Better yet use a StringBuilder
String cards="Hello my Name is Jon, nice to meet you";
System.out.println("Input String = " + cards);
String[] splt = cards.split(" ");
StringBuilder sb = new StringBuilder();
for (int iter = 0; iter < shuffled.length; iter ++){
sb.append(shuffle(splt[iter]) + " ");
}
String shuffled = sb.toString();

You should split the sentence into words and then scramble the words:
String[] words = sentence.split(" ");
for(String word : words)
word = shuffle(word);
Then concat the word together to a sentence.

Related

How to reverse words in a string but keep punctuation in the right place? [duplicate]

This question already has answers here:
Reverse String Word by Word in Java
(37 answers)
Closed 7 years ago.
I have written the following code to reverse an input String:
Scanner s = new Scanner(System.in);
System.out.println("Please enter a sentence:");
String sentence = s.nextLine();
String[] words = sentence.split(" ");
String reversedSentence = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
reversedSentence += words[i] + " ";
}
System.out.println(reversedSentence);
However it is not giving me the result I want. I need the punctuation to be part of the word it is attached to, but still to switch to the right side of the word. For example if you input
“The quick brown fox jumps over the lazy dog”
I want the output to be
“dog lazy the over jumps fox brown quick The”
What I am actually getting is:
dog” lazy the over jumps fox brown quick “The
If you just want to handle double quotes at the start and end of the input, just reverse the substring and add them later. E.g.
if (sentence.startsWith("\"") && sentence.endsWith("\"")) {
sentence = sentence.substring(1, sentence.length()-1);
}
and finally after splitting, reversing and concatenating print:
System.out.println('"' + reversedSentence + '"');
Also 2 recommendations :
1) Your for loop leaves a trailing space. Don't add a space for the last word
2) You should use a StringBuilder to concatenate strings. E.g.
StringBuilder reversedSentence = new StringBuilder();
for (int i = words.length - 1; i > 0; i--) {
reversedSentence.append(words[i]).append(' ');
}
reversedSentence.append(words[0]);
System.out.println('"' + reversedSentence.toString() + '"');
If the punctuation opens and closes as well. Like in your example. You could use something like this:
It's very dirty. I'll edit it later. I don't do java much.
String[][] punctuations = new String[][] {
{"(", ")"},
{"“", "”"}
};
for (String[] punctuation : punctuations) {
if (sentence.contains(punctuation[0])) {
int index_0 = sentence.indexOf(punctuation[0]);
int index_of_next_space = sentence.indexOf(" ", index_0);
String old_string_0 = sentence.substring(index_0, index_of_next_space);
String new_string_0 = old_string_0.replace(punctuation[0], "") + punctuation[1];
int index_1 = sentence.indexOf(punctuation[1]);
int index_of_last_space = sentence.lastIndexOf(" ", index_1);
String old_string_1 = sentence.substring(index_of_last_space+1, index_1 + 1);
String replaced_string_1 = punctuation[0] + old_string_1.replace(punctuation[1], "");
sentence = sentence.replace(old_string_0, new_string_0);
sentence = sentence.replace(old_string_1, replaced_string_1);
}
}
Now reverse your string.
Input:
“The (quick brown's) fox jumps over the lazy dog”
Output:
“dog lazy the over jumps fox (brown's quick) The”
This can be improved. Like I said before, I don't do java much :/.
Break the string into array and use Collections.reverse() as follows:
public class StringReverse {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter a sentence:");
String sentence = s.nextLine();
String[] array = sentence.replaceAll("\\“|”", "").split(" ");
StringBuilder sb = new StringBuilder();
List<String> list = Arrays.asList(array);
Collections.reverse(list);
array = (String[]) list.toArray();
for (int i = 0; i < array.length; i++) {
sb.append(array[i]).append(" ");
}
System.out.println(sentence.charAt(0)
+ sb.toString().replaceAll(" $", "")
+ sentence.charAt(sentence.length() - 1));
s.close();
}
}
With Java 8 Arrays.stream, it is as simple as:
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class StringReverse {
Scanner s = new Scanner(System.in);
System.out.println("Please enter a sentence:");
String sentence = s.nextLine();
StringBuilder sb = new StringBuilder();
Arrays.stream(sentence.replaceAll("\\“|”", "").split(" "))
.collect(Collectors.toCollection(ArrayDeque::new))
.descendingIterator()
.forEachRemaining(e -> sb.append(e).append(" "));
System.out.println(sentence.charAt(0)
+ sb.toString().replaceAll(" $", "")
+ sentence.charAt(sentence.length() - 1));
s.close();
}

Accept 5 names and print the longest name?

I want to the longest name for 5 given names. I think I should use compareTo() method or length()?
Output must be like this :
enter 5 names :
Joey
Mark
Catherine
Zachery
Foster
Longest name is Catherine.
What method should I use and how? This is my code so far:
Scanner x = new Scanner(System.in);
String name = ""
System.out.print("Enter 5 names");
name = x.nextLine();
name2 = x.nextLine();
name3 = x.nextLine();
name4 = x.nextLine();
name5 = x.nextLine();
if(name.compareTo(name2)>0) //is this method right?
.compareTo tells you which string comes first in lexicographic order (<0 if s1 < s2, 0 if s1==s2, >0 if s1>s2)
String s1 = "abc";
String s2 = "def";
s1.compareTo(s2) < 0;
.length() returns the length of a string
s1.length()==3;
In your case, you need to compare based on length, so you need the latter. If it's only 5 names, you can take the first and assume it's the longest, and then read the others one by one by keeping the "longest so far" saved and comparing them as they come. After all, you only care about the longest.
If you wanted them to be sorted by length, while still keeping them all, you'd need to store them in some sort of collection (list, array), then sort it based on length.
The problem is easy enough, so I won't provide directly the code, try to grok it yourself, you can do it :)
import java.util.Scanner;
public class LenghtyName {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
/*
Instead of declaring 5 different String variable
just use String array with size = 5
*/
String[] names = new String[5];
System.out.print("Enter 5 names :");
names[0] = x.nextLine();
names[1] = x.nextLine();
names[2] = x.nextLine();
names[4] = x.nextLine();
names[5] = x.nextLine();
//Assume lenthyName as empty String
String lengthyName = "";
/*
Iterate over String array using for-each loop
*/
for (String name : names) {
/*
-Check null to avoid NullPointerException
-Trim the left and right blank space in name by #trim()
-Compare current name length with lengthyName if greater
replace the lengthyName by current name.
*/
if (name != null && name.trim().length() > lengthyName.length()) {
lengthyName = name;
}
}
/*
Print length name
*/
System.out.println("Longest name is " + lengthyName);
}
}
What about this?
Scanner in = new Scanner(System.in);
// no need to have 5 all over the code.
// Define it once to avoid "magic nubmers"
int namesCount = 5;
// fun fact: shortest name is always "". We don't have to use null
String longestName = "";
System.out.print("Enter " + nameCount + " names:");
for (int i=0; i< nameCount; i++){
// store new name from user
String candidate = in.readLine();
// is this one longer than the current longest?
if (longestName.length() < candidate.length()){
// found a longer name
longestName = candidate;
}
}
System.out.println("Longest name is " + longestName);
This gives up storing the names, as it seems you only use the longest one anyway. It also generalizes the number of names to iterate, and most importantly the variable names are meaningful names.
Here's a solution that should work:
public class LongestWord {
public static String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
}
public static void main(String[] args) {
String[] toppings = {"Cheeddddddddddse", "Pepperoni", "Black Olivesddd"};
String longestString = getLongestString(toppings);
System.out.format("longest string: '%s'\n", longestString);
}
}
An easy way would be a for loop to read 5 names and find the length for largest name. Using the for loop avoids the creation of 5 deterrent string variables.
If you want to use those names later you can go for String array.
public static void main(String[] args) throws IOException {
Scanner x = new Scanner(System.in);
String name = "";
String maxName = "";
int maxLength = 0;
System.out.println("enter 5 name :");
for (int i = 0; i < 5; i++) { // read 5 names
name = x.nextLine();
if (maxLength < name.length()) { // check longest name
maxLength = name.length();
maxName = name; // store in temp variable to show
}
}
System.out.println("Longest name is " + maxName); // print largest name
}
Output:
enter 5 name :
raj
sita
gita
mukherjee
rita
Longest name is mukherjee
Here's a solution that should work with any number of entries:
Scanner x = new Scanner(System.in);
String name = "", temp="";
while (x.hasNextLine()){
temp = x.nextLine();
if (temp.length() > name.length()) name = temp;
}
System.out.println("Longest is " + name);
You'll need to Ctrl + Z to end the inputStream on Windows
this is my code for comparing 3 input strings by their length:
public static void main(String[] args) {
String string1 , string2 , string3;
Scanner input = new Scanner(System.in);
System.out.println("Enter three string names to compare");
string1 = input.nextLine();
string2 = input.nextLine();
string3 = input.nextLine();
if (string1.length()>string2.length()) {
if (string1.length() > string3.length())
System.out.println("String 1 has the longest length , length = "+string1.length());
}
if (string2.length()>string1.length()){
if(string2.length()>string3.length())
System.out.println("String 2 has the longest length , length = "+string2.length());
}
if (string3.length()>string1.length()) {
if (string3.length() > string2.length())
System.out.println("String 3 has the longest length , length = " + string3.length());
}
}
//SIMPLE JAVA SOLUTION
class GFG
{
String longest(String names[], int n)
{
String res="";
for(int i=0;i<n;i++)
{
if(res.length()<names[i].length())
{
res=names[i];
}
}
return res;
}
}

Count word length with occurrence

I am doing a program to count the length of each word followed by the number of occurrences of that length.
For example:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
So far I tried this,
import java.util.Scanner;
class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
String[] arr = s.split(" ");
String str = "";
int [] len = new int[arr.length];
int [] count = new int[arr.length];
int c = 0;
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
for(int j=0;j<arr.length;j++){
if(str.length() == arr[j].length()){
count[i] = ++c;
}
}
c = 0;
}
for(int i=0;i<len.length;i++){
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
}
}
There is a problem in my logic and that's why it's output is like this:
Enter a String :I love my work
The word count is -
No. of words of length 1 are 1.
No. of words of length 2 are 1.
No. of words of length 4 are 2.
No. of words of length 4 are 2.
Any suggestion how to fix that or any other simpler way to do it(without using collections, maps).
You can replace array with a Map<Integer,Integer>, It will easiar.
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String :");
String s = sc.nextLine();
String[] arr = s.split(" ");// get the words
Map<Integer, Integer> lengthVsCount=new HashMap<>(); // length vs count
for(String i:arr){ // iterate array
Integer val=lengthVsCount.get(i.length()); // searching count
if(val!=null){ // if count is there
lengthVsCount.put(i.length(),val+1);// increment count by one
}else{ // count not there
lengthVsCount.put(i.length(),1); // add count as one
}
}
for (Map.Entry<Integer,Integer> entry:lengthVsCount.entrySet()) {
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue() + ".");
}
You should use a map:
public static void main(String[] args) {
final String input = "I love my work";
final String[] words = input.split(" ");
final Map<Integer, Integer> occurencesMap = new HashMap<Integer, Integer>();
for (final String word : words) {
final int lenght = word.length();
if (occurencesMap.get(lenght) == null) {
occurencesMap.put(lenght, 1);
} else {
occurencesMap.put(lenght, occurencesMap.get(lenght) + 1);
}
}
System.out.println("The word count is -");
final Iterator<Map.Entry<Integer, Integer>> entries = occurencesMap.entrySet().iterator();
while (entries.hasNext()) {
final Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("No. of words of length " + entry.getKey() + " are " + entry.getValue());
}
}
class Demo{
public static void main(String[] args){
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String :");
s=sc.nextLine();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (String str : s.split(" ")) {
int key = str.length();
if (map.containsKey(key)) {
map.put(key, map.get(key)+1);
}
else {
map.put(key, 1);
}
}
Iterator<Integer> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
int key = iterator.next();
System.out.println("No. of words of length " + key + " are " + map.get(key) + ".");
}
}
}
Here,
for(int i=0;i<arr.length;i++){
str = arr[i];
len[i] = str.length();
You should check if len[i] is not a value already in the array. So use
int k;
for(k=0 ; k<i ; k++ )
if( len[i]==len[k] ) //if a match was found
break; //break out of the loop
if(k!=i) //will be true if the break has been executed
{
len[i]=0; //set to 0
continue; //go back to the loop
}
Just after that and use
for(int i=0;i<len.length;i++){
if(len[i]!=0)
System.out.println("No. of words of length "+len[i]+" are "+count[i]+".");
}
When printing the results.

Print Words In String Backwards

So I'm having a bit of trouble with my Computer Science class. I need to write some code that will take a string and print it backwards in reverse word order. He told me to find an empty space, then print from there and then keep searching....and repeat this until the end of the string. I typed my code out and all it does it print the first word 3 times. I know this will probably seem obvious to you guys.
public class Backwords
/*
* Gets words from main and prints in reverse order
*/
public static String BackwardsString(String str)
{
String str1 = (" " + str);
String answer = (" ");
int lastpos = str1.length();
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
return answer;
}
public static void main(String [] args)
{
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in); //gets string input
String str = firststr.next();
System.out.println(BackwardsString(str));
}
}
Set answer back to answer = "" before the second nested for loop
for(int currpos = str.length(); currpos >= 0; currpos--) //shazam
{
if (str1.charAt(currpos) == ' ')
{
answer = "";
for (int p = currpos+1; p <lastpos; p++) //majicks
answer = answer + str1.charAt(p);
lastpos = currpos;
System.out.println(answer);
}
}
You should use StringBuilder instead of String here since there can be lot of String concatenation which may create more object in the heap.
Using StringBuilder you can do this easy way too.
Eg:
public static String BackwardsString(String str) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
return stringBuilder.reverse().toString();
}
public static void main(String[] args) {
System.out.println("Enter a string : ");
Scanner firststr = new Scanner(System.in);
String str = firststr.next();
System.out.println(BackwardsString(str));
}
try this
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string ");
String str = sc.nextLine();
String[] strArray = str.split(" ");
StringBuilder reverseString = new StringBuilder("");
for (int i = strArray.length - 1; i >= 0; i--) {
reverseString.append(strArray[i]+" ");
}
System.out.println("Reverse of string is : "+reverseString.toString());
You'd probably have an easier time splitting the string:
String[] words = str1.split(" ");
Then you'd work on each word[i] reversing it, you could break it down to a char array, or use a stringbuilder as others have suggested, up to you on what you think is appropriate for your class.

java how to separate words in a string and store each seperate word in a variable

I need my scanner input to be broken down into separate words or wherever a space occurs. I have it somewhat working, however if the line has too many or too few words, i can't get it to work. Please help me. I have a Monday deadline. Here is my current code.
//import java.util.Scanner;
public class durodyne {
public static void main(String[] args) {
String name;
String part1;
String remain1;
String part2;
String part3;
String part4;
String part5;
String part6;
String part7;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Full Product Name");
name = keyboard.nextLine();
int space=name.indexOf(' ');
part1 = name.substring(0, space);
int space2 = name.indexOf(' ', space + 1);
int space3 = name.indexOf(' ', space2 + 1);
part2 = name.substring(space, space2);
int space4 = name.indexOf(' ', space3 + 1);
int space5 = name.indexOf(' ', space4 + 1);
part3 = name.substring(space2, space3);
int space6 = name.indexOf(' ', space5 + 1);
int space7 = name.indexOf(' ', space6 + 1);
part4 = name.substring(space3, space4);
part5 = name.substring(space4, space5);
part6 = name.substring(space5, space6);
part7 = name.substring(space6, space7);]
}
//your initialization
List<String> names = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Full Product Name");
name = keyboard.nextLine();
names = Arrays.asList(name.split(" "));
//your code
String[] nameParts = name.split(" ");
for(String part: nameParts) {
// Use part as required
}
Check out String.split();
Here is one example: Supposing that you store the input into a string named 'blah'. you can do this:
String blah = "lass ias sfsf sfsfs sfsfs sfsdfs sfsdfs sfsdfs jj";
String [] parts = blah.split(" "); //all parts stored in an array
//Printing the array to show you the array content.
for(String s : parts) {
System.out.println("parts : " + s);
}
It will be better to parse the input string using something like this.
int wordCount=0;
String words[MaxPossiWords];
int j=0;
char ch;
for(int i=0;i<sent.length();i++) {
ch = sent.charAt(i);
if( ch == ' '){
words[wordCount++]= new String(curCharArray);
j=0;
}
curCharArray[j++]=sent.charAt(i);
}
//finished parsing the line to words.
for(int i=0;i<wordCount;i++)
System.out.println(words[i]+", ");
This way make the parsing little bit dynamic. If you want more dynamism, you can use ArrayList collection instead of String array of words.
Happy Coding.

Categories

Resources