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);
}
}
Related
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));
}
}
.
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.
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;
}
After meddling with arrays and countless google searches, I can't seem to find the answer.
public static void main(String args[]){
String[] names = new String[4]; //I want to fill this up with data from country
country(names);
System.out.println(names(0)) //I want this to display Madrid
}
public static void country(String[] names){
names[0] = "Madrid";
names[1] = "Berlin";
return;
}
I'm not sure if this explains what I'm trying to do.
You really have to work on java syntax. Your code is quite simple so it should work immediately, but you have to be careful with some details, here is a code which works fine:
public static void main(String args[]) {
String[] names = new String[4]; //I want to fill this up with data from country
country(names);
System.out.println(names[0]); //I want this to display Madrid
}
public static void country(String[] names) {
names[0] = "Madrid";
names[1] = "Berlin";
}
As you can see I use [ ] to access a value at a specific index in an array. I don't use any return in a void method neither.
You don't need to return the array in country method because java don't pass arguments on value (see http://javarevisited.blogspot.fr/2012/12/does-java-pass-by-value-or-pass-by-reference.html)
So I really advice you to read any tutorial you can find about java syntax to improve yourself for now.
Arrays are accessed using [], not (). You are also missing a semicolon in the printing statement.
Change:
System.out.println(names(0))
To:
System.out.println(names[0]); // use [] instead of () and add a semicolon
Also, the method country(String[] names) returns void so you don't need the return statement at the end of it (it's implied).
Here's how your code should look like:
public static void main(String args[]){
String[] names = new String[4]; //I want to fill this up with data from country
country(names);
System.out.println(names[0]); // use [] instead of () and add a semicolon
}
public static void country(String[] names){
names[0] = "Madrid";
names[1] = "Berlin";
}
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.