How to code this specific for loop in Java? - java

I have created an average word length checker in Python and I want to convert it into Java.
This is the for loop in Python:
for p in "!£$€%^&*()-_=+`¬¦[]{};:'##~,.<>/?|":
sentence = sentence.replace(p, '')
words = sentence.split()
I want to code this in Java.
Here is what I've tried in Java:
public class AverageWordLength {
public void average_word_length(String sentence){
String characters = "!£$€%^&*()-_=+`¬¦[]{};:'##~,.<>/?|"
for (char p: characters){
}
}
Any hints on how to do this?

String has a split method to split a string with a regular expression
With the stream method the array is converted in a stream.
With the map for each part the length is calculated
And at last the collect returns the average of the length
public class WordLengthChecker {
public static void main(String[] args) {
System.out.println(average_word_length("String_to_split[on(special]characters") );
}
public static double average_word_length(String sentence){
String characters = "[!£$€%^&*()\\-_=+`¬¦\\[\\]{};:'##~,.<>/?|]";
return Arrays.stream(sentence.split(characters))
.map(i -> i.length())
.collect(Collectors.averagingDouble(i -> i));
}
}
.

Related

How do I check if the number of occurrences of two words in a String is Equal without using loops?

I am trying to find out if there is the same number of occurrences "dog" and "cat" are in the given String.
It should return true if they are equal, or false otherwise. How can I find out this without while, for etc. loops?
This is my current process
class Main {
public static boolean catsDogs(String s) {
String cat = "cat";
String dog = "dog";
if (s.contains(cat) && s.contains(dog)) {
return true;
}
return false;
}
public static void main(String[] args) {
boolean r = catsDogs("catdog");
System.out.println(r); // => true
System.out.println(catsDogs("catcat")); // => false
System.out.println(catsDogs("1cat1cadodog")); // => true
}
}
With java9+ the regex matcher has a count method:
public static boolean catsDogs(String s) {
Pattern pCat = Pattern.compile("cat");
Pattern pDog = Pattern.compile("dog");
Matcher mCat = pCat.matcher(s);
Matcher mDog = pDog.matcher(s);
return (mCat.results().count() == mDog.results().count());
}
You can use the following example by replacing the string (in case you don't want the split to be placed) :
public static boolean catsDogs(String s) {
return count(s,"cat") == count(s,"dog");
}
public static int count(String s, String catOrDog) {
return (s.length() - s.replace(catOrDog, "").length()) / catOrDog.length();
}
public static void main(String[] args) {
boolean r = catsDogs("catdog");
System.out.println(r); // => true
System.out.println(catsDogs("catcat")); // => false
System.out.println(catsDogs("1cat1cadodog")); // => true
}
Here's a couple of single-line solutions based on Java 9 Matcher.result() which produces a stream of MatchResult corresponding to each matching subsequence in the given string.
We can also make this method more versatile by providing a pair of regular expressions as arguments instead of hard-coding them.
teeing() + summingInt()
We can turn the stream of MatchResesult into a stream of strings by generating matching groups. And collect the data using collector teeing() expecting as its arguments two downstream collectors and a function producing the result based on the values returned by each collector.
public static boolean hasSameFrequency(String str,
String regex1,
String regex2) {
return Pattern.compile(regex1 + "|" + regex2).matcher(str).results()
.map(MatchResult::group)
.collect(Collectors.teeing(
Collectors.summingInt(group -> group.matches(regex1) ? 1 : 0),
Collectors.summingInt(group -> group.matches(regex2) ? 1 : 0),
Objects::equals
));
}
collectingAndThen() + partitioningBy()
Similarly, we can use a combination of collectors collectingAndThen() and partitioningBy().
The downside of this approach in comparison to the one introduced above is that partitioningBy() materializes stream elements as the values of the map (meanwhile we're interested only their quantity), but it performs fewer comparisons.
public static boolean hasSameFrequency(String str,
String regex1,
String regex2) {
return Pattern.compile(regex1 + "|" + regex2).matcher(str).results()
.map(MatchResult::group)
.collect(Collectors.collectingAndThen(
Collectors.partitioningBy(group -> group.matches(regex1)),
map -> map.get(true).size() == map.get(false).size()
));
}

Creating a static method that meshes two strings together

We recently started learning about static methods and for this assignment we are making a "String Helper" program that creates a few static methods that modify strings, and this is the task for one of them:
meshStrings: This method takes in two strings via parameters, meshes them together, and returns the meshed strings. Meshing alternates the each character in the first string with every character in the next string. If there are not enough characters to fully mesh then the rest will be appended to the end. For instance if the two strings were "harp" and "fiddle" the returned string will be hfairdpdle.
Here's the start of what I have, I don't have much:
public class StringHelper {
public static String meshStrings (String string1, String string2)
{
}
Driver class:
public class StringHelperTester {
public static void main (String[] args)
{
System.out.print(StringHelper.meshStrings("fiddle", "harp"));
}
I assume you'll have some type of for loop that prints out the charAt length of each string but I'm not exactly sure the best way to set it up. Help is appreciated.
the best way to enchance your skills is to just try ...
public static String meshStrings (String string1, String string2) {
StringBuffer buff = new StringBuffer();
int max = Math.max(string1.length(), string2.length());
for(int i = 0; i < max; i++) {
if(i < string1.length()) {
buff.append(string1.charAt(i));
}
if(i < string2.length()) {
buff.append(string2.charAt(i));
}
}
return buff.toString();
}
KISS : keep it simple and stupid. then you can enhance this code if you want, it's not optimal.

Java substring string when specific string occurs

i need help to substring a string when a a substring occurs.
Example
Initial string: 123456789abcdefgh
string to substr: abcd
result : 123456789
I checked substr method but it accept index position value.I need to search the occurrence of the substring and than pass the index?
If you want to split the String from the last number (a), then the code would look like this:
you can change the "a" to any char within the string
package nl.testing.startingpoint;
public class Main {
public static void main(String args[]) {
String[] part = getSplitArray("123456789abcdefgh", "a");
System.out.println(part[0]);
System.out.println(part[1]);
}
public static String[] getSplitArray(String toSplitString, String spltiChar) {
return toSplitString.split("(?<=" + spltiChar + ")");
}
}
Bear in mind that toSplitString.split("(?<=" + spltiChar + ")"); splits from the first occurrence of that character.
Hope this might help:
public static void main(final String[] args)
{
searchString("123456789abcdefghabcd", "abcd");
}
public static void searchString(String inputValue, final String searchValue)
{
while (!(inputValue.indexOf(searchValue) < 0))
{
System.out.println(inputValue.substring(0, inputValue.indexOf(searchValue)));
inputValue = inputValue.substring(inputValue.indexOf(searchValue) +
searchValue.length());
}
}
Output:
123456789
efgh
Use a regular expression, like this
static String regex = "[abcd[.*]]"
public String remove(String string, String regex) {
return string.contains(regex) ? string.replaceAll(regex) : string;
}

Find variable ID's in a string with random text

I have something like the following as a String: http://pastebin.com/8QxSC8zJ
What I actually need are the SteamIDs, e.g. "STEAM_0:1:49093894". The part "STEAM_0" is always identical, but the two numbers after that are variable. What would be the best way to retrieve these ID's as a String array?
Update: I looked up regular expressions like Jim Garrison suggested and came up with the following:
String out = //see pastebin
String[] substrings = out.split("\\s+"); //splits at whitespace
for(String a : substrings) {
if(a.matches("STEAM_0.*")) {
System.out.println(a);
//add to string array/list/whatever
}
}
This does indeed print all SteamID's (and I could add them to a String-Array), but how would I do this if there would be no whitespaces in the String?
If you want String array you have to know the length, so as to initialize the array. Let's say it is 3. You can do :
public class Main {
public static void main(String[] args) {
public static void main(String[] args) {
String Str = new String("STEAM_0:1:49093894");
String[] array= new String[2];
array[0]=Str.substring(8,9) ;
array[1]=Str.substring(9);
}
}

Java class Anagrams

Im new to the java programming language and need help writing a class Anagrams that prints the permutations of words in a sentence. Example: red car -> red car, car red. This is what i have written so far and i think im on the right track and even though my code is not finished, i would at least like to get it to run.
import javax.swing.JOptionPane;
public class Anagrams
{
private String x;
private char[] xarray;
private String[] words;
public void Anagrams(String phrase1)
{
x = phrase1;
}
public void printPerms()
{
int perms = 0;
xarray = x.toCharArray();
for (int i = 0; i < x.length(); i++)
{
if(xarray[i] == ' ') perms = perms + 1;
}
words = x.split(" ");
for (int i = 0; i < perms; i++)
{
System.out.println(words[i]);
}
}
public void main(String args[])
{
String phrase1 = JOptionPane.showInputDialog("Enter phrase 1.");
Anagrams(phrase1);
printPerms();
}
}
This is the error i get when i try to run.
Exception in thread "main" java.lang.NoSuchMethodError: main
Right now im just trying to get my program to run not print out the permutations. I think i can figure that out once it at least print something out. Can someone tell me why it doesnt run and how do you get input from the user like c++ cin>>, if there is another way other than JOptionPane.
Thanks
A main method needs to be static.
How about this:
public static void main(String args[])
{
String phrase1 = JOptionPane.showInputDialog("Enter phrase 1.");
new Anagrams(phrase1).printPerms();
}
Even After Declaring your main method as static you may or may not be required to make all other methods as static(If calling methods dirctly without use of objects make methods as static).Because a static method can call or use only static data memebers or methods.
And in your code because you have defined all the methods in the same class which contains main method you need to make other methods also as static.
The method should return true if the two arguments are anagrams of each other, false if they are not.
For example, anagram(“glob”, “blog”) would return true;and anagram(“glob”, “blag”) false.
Assumes that the input strings will contain only letters and spaces. Treat upper- and lower-case letters as identical, and ignore spaces.
<br/> Uses the following algorithm:
<ul> <li> clean input strings from spaces and convert to lower case
</li> <li>convert to char array and sort them
</li> <li>if sorted arrays are identical, words are anagrams
</li></ul>
*/
public static boolean anagram(String str1, String str2)
{
//handle nulls
if(str1==null && str2==null)
return true;
else if( (str1==null && str2!=null) || (str2==null && str1!=null) )
return false;
//clean input strings from spaces and convert to lower case
String s1 = str1.replace(" ", "").toLowerCase();
String s2 = str2.replace(" ", "").toLowerCase();
//convert to char array and sort them
char[] cArr1 = s1.toCharArray();
char[] cArr2 = s2.toCharArray();
java.util.Arrays.sort(cArr1);
java.util.Arrays.sort(cArr2);
//if sorted arrays are identical, words are anagrams
s1 = new String(cArr1);
s2 = new String(cArr2);
return s1.equals(s2);
}
public static void main(String[] args)
{
//test: anagram(“glob”, “blog”) would return true; anagram(“glob”, “blag”) false.
System.out.println("anagram(“glob”, “blog”):"+(anagram("glob", "blog")));
System.out.println("anagram(“glob”, “blag”):"+(anagram("glob", "blag")));
}
You are missing static in:
public void main(String args[])
The main method needs to be static.
Also you are calling printPerms from main directly (without an object) so it must be made static as well or call them on a Anagram class object.
You are missing the new keyword while creating the object:
Anagrams(phrase1);
printPerms();
try
new Anagrams(phrase1).printPerms();
Also there is no Anagram class constructor that takes a String. What you have is a method named Anagram as you've specified the return type.
public void Anagrams(String phrase1) {
drop the void.

Categories