Getting a string to accept a string[] as a param? - java

I am currently trying to create a method that turn words into their plural equivalent. In doing this I have some cascaded if's that use the .endsWith() method.
I have a string array of consonants(+y) which I want to use as a parameter for the endsWith() method. But it says that I need to change type consonantandY method to String and not String[]. If I do that, I can't make an array...
How do I get around this?
private String regularPluralForm(String word) {
String s2 = "";
if(word.endsWith("s)")) {
s2 = "es";
} else if(word.endsWith("x)")) {
s2 = "es";
} else if(word.endsWith("z")) {
s2 = "es";
} else if(word.endsWith("ch")) {
s2 = "es";
} else if(word.endsWith("sh")) {
s2 = "es";
} else if(word.endsWith(consonantAndY)) {
}
String correctWord = word+s2;
return correctWord;
}
private static final String[] consonantAndY = {"by","cy","dy","fy",
"gy","hy","jy","ky"
,"ly","my","ny"
,"py","qy","ry","sy"
,"ty","vy","wy","xy"
,"yy","zy"};
}

Rather than looping over consonantAndY, calling endsWith on each element of that array, you can use a regular expression.
} else if (word.matches(".*[bcdfghjklmnpqrstvwxyz]y")) {

Iterate over the array
else {
boolean matches = false;
for(String s : constantAndY) {
if (word.endsWith(s)) {
matches = true;
break;
}
}
but better is apparently the answer above with java 8

With java 8 you can do
if( Arrays.asList(consonantAndY).stream().anyMatch(t -> word.endsWith(t)) ){
// do something
}
Demo

Could make a helper method called endsWith that takes the array as a parameter.
int consonantIndex = -1;
if (...) { ... }
else if((consonantIndex = endsWith(word, consonantAndY)) != -1) {
s2 = consonantAndY[consonantIndex];
}
private int endsWith(String s, String... suffixes) {
for (int i = 0; i < suffixes.length; i++) {
if (s.endsWith(suffixes[i])) {
return i;
}
}
return -1;
}

Related

Problems with sorting an Array in Java

I´m a bloody beginner trying to write a lil programm to check if 2 words are anagrams. So far all the whitespaces within the words get deleted but apparently there's an error with my Arrays.sort() but I can´t see it. Why and where´s the error in my Arrays.sort() line and how could I solve it?
Edit: If I leave the Arrays.sort() out like this it compiles and works so apparently there's only a problem with that line. If I leave them in it points to array and says error: can not find symbol
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
int word1 = w1.length();
String w2 = wordTwo.replaceAll("\\s", "");
int word2 = w2.length();
boolean anagrammStatus = false;
if(word1 == word2)
{
anagrammStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
//Arrays.sort(charArrayWordOne);
//Arrays.sort(charArrayWordTwo);
anagrammStatus = charArrayWordOne.equals(charArrayWordTwo);
}
if(anagrammStatus == false)
{
System.out.println("Anagram");
}
else;
{
System.out.println("No Anagram");
}
}
This should do the trick:
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
String w2 = wordTwo.replaceAll("\\s", "");
// No need to keep the length variables
boolean anagramStatus = false;
// Check if the strings are equal to begin with, use equals and not == operator
if(w1.equals(w2))
{
anagramStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
Arrays.sort(charArrayWordOne);
Arrays.sort(charArrayWordTwo);
// Compare arrays using the Arrays.equals method to avoid comparing the object references
anagramStatus = Arrays.equals(charArrayWordOne, charArrayWordTwo);
}
// Use simple boolean logic in your condition here, or again, always use == instead of =
if (anagramStatus)
{
System.out.println("Anagram");
}
else
{
System.out.println("No Anagram");
}
}

How to replace a string with a regex in java using nested groups

I have the format line
"123","45","{"VFO":[B501], "AGN":[605,B501], "AXP":[665], "QAV":[720,223R,251Q,496M,548A,799M]}","4"
it can be longer but it always contains
"number","number","someValues","digit"
I need to wrap values inside someValues with quotes
for test string expected result should be.
"123","45","{"VFO":["B501"], "AGN":["605","B501"], "AXP":["665"], "QAV":["720","223R","251Q","496M","548A","799M"]}","4"
Please suggest simplest solution in java.
P.S.
my variant:
String valuePattern = "\\[(.*?)\\]";
Pattern valueR = Pattern.compile(valuePattern);
Matcher valueM = valueR.matcher(line);
List<String> list = new ArrayList<String>();
while (valueM.find()) {
list.add(valueM.group(0));
}
String value = "";
for (String element : list) {
element = element.substring(1, element.length() - 1);
String[] strings = element.split(",");
String singleGroup = "[";
for (String el : strings) {
singleGroup += "\"" + el + "\",";
}
singleGroup = singleGroup.substring(0, singleGroup.length() - 1);
singleGroup = singleGroup + "]";
value += singleGroup;
}
System.out.println(value);
EDITED
OK, here is the shortest way i found, it works very nicely in my opinion, except for the comma and the bracket which i had to add manually... somebody might be able to do it straight away but i found it tricky to handle replacements with nested groups.
import java.util.*;
import java.lang.*;
import java.io.*;
Pattern p = Pattern.compile("(\\[(\\w+))|(,(\\w+))");
Matcher m = p.matcher("\"123\",\"45\",\"{\"VFO\":[B501], \"AGN\":[605,B501], \"AXP\":[665], \"QAV\":[720,223R,251Q,496M,548A,799M]}\",\"4\"");
StringBuffer s = new StringBuffer();
while (m.find()){
if(m.group(2)!=null){
m.appendReplacement(s, "[\""+m.group(2)+"\"");
}else if(m.group(4)!=null){
m.appendReplacement(s, ",\""+m.group(4)+"\"");
}
}
m.appendTail(s);
print(s);
As I commented above, I think the real solution here is to fix the thing that's generating this malformed output. In the general case I don't believe it's possible to parse correctly: if the strings contain embedded bracket or comma characters then it becomes impossible to determine which parts are which.
You can get pretty close, though, by simply ignoring all quote characters and tokenizing the rest:
public final class AlmostJsonSanitizer {
enum TokenType {
COMMA(','),
COLON(':'),
LEFT_SQUARE_BRACKET('['),
RIGHT_SQUARE_BRACKET(']'),
LEFT_CURLY_BRACKET('{'),
RIGHT_CURLY_BRACKET('}'),
LITERAL(null);
static Map<Character, TokenType> LOOKUP;
static {
Map<Character, TokenType> lookup = new HashMap<Character, TokenType>();
for (TokenType tokenType : values()) {
lookup.put(tokenType.ch, tokenType);
}
LOOKUP = Collections.unmodifiableMap(lookup);
}
private final Character ch;
private TokenType(Character ch) {
this.ch = ch;
}
}
static class Token {
final TokenType type;
final String string;
Token(TokenType type, String string) {
this.type = type;
this.string = string;
}
}
private static class Tokenizer implements Iterator<Token> {
private final String buffer;
private int pos;
Tokenizer(String buffer) {
this.buffer = buffer;
this.pos = 0;
}
#Override
public boolean hasNext() {
return pos < buffer.length;
}
#Override
public Token next() {
char ch = buffer.charAt(pos);
TokenType type = TokenType.LOOKUP.get(ch);
// If it's in the lookup table, return a token of that type
if (type != null) {
pos++;
return new Token(type, null);
}
// Otherwise it's a literal
StringBuilder sb = new StringBuilder();
while (pos < buffer.length) {
ch = buffer.charAt(pos++);
// Skip all quote characters
if (ch == '"') {
continue;
}
// If we've found a different type of token then stop
if (TokenType.LOOKUP.get(ch) != null) {
break;
}
sb.append(ch);
}
return new Token(TokenType.LITERAL, sb.toString());
}
#Override
public boolean remove() {
throw new UnsupportedOperationException();
}
}
/** Convenience method to allow using a foreach loop below. */
static Iterable<Token> tokenize(final String input) {
return new Iterable<Token>() {
#Override
public Iterator<Token> iterate() {
return new Tokenizer(input);
}
};
}
public static String sanitize(String input) {
StringBuilder result = new StringBuilder();
for (Token token : tokenize(input)) {
switch (token.type) {
case COMMA:
result.append(", ");
break;
case COLON:
result.append(": ");
break;
case LEFT_SQUARE_BRACKET:
case RIGHT_SQUARE_BRACKET:
case LEFT_CURLY_BRACKET:
case RIGHT_CURLY_BRACKET:
result.append(token.type.ch);
break;
case LITERAL:
result.append('"').append(token.string).append('"');
break;
}
}
return result.toString();
}
}
If you wanted to you could also do some sanity checks like ensuring the brackets are balanced. Up to you, this is just an example.

how to Extract a Field from a line wit tab delimer in java

I have a c++ method extractField that I would like to use to axtract some fields from a line each field delimited by '\t' it works well in c++ could someone help me with the syntax for java. I would like to apply a similler method_ here is what I have:
String ExtractField(String aline,int fieldnumber){
Int seppos;
String field;
for (int fld = 0: fld< fieldnumber;fld++){
seppos = aline.Pos('\t');
field = aline.SubString(1,seppos-1);
aline.delete(1.seppos);
}
If(seppos>0){return field;}
else{return aline;}
}
The folowing is in java, rewrote it for you ;)
private String ExtractField(String aline, int fieldnumber)
{
Integer seppos = new Integer();
String field;
for (int fld = 0; fld < fieldnumber; fld++)
{
seppos = aline.indexOf('\t');
field = aline.substring(1, seppos - 1);
//aline.delete(1.seppos); what does this do?
}
If(seppos > 0)
{
return field;
}
else
{
return aline;
}
}
I think this will do what you want.
public String extractField(String aline, int fieldNumber) {
String[] fields = aline.split("\t");
//Illegal field NUmber.
if (fieldNumber < 0 || fieldNumber >= fields.length) {
return null;
}
return fields[fieldNumber];
}
Use StringTokenizer
StringTokenizer st = new StringTokenizer(aline, "\t");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

Parameter passing in Java problems

I am new to java, and have been writing a program to check if a given string is periodic or not.A string is not periodic if it cannot be represented as a smaller string concatenated some number of times. Example "1010" is periodic but "1011" is not. Here is my code. It compiles, but the problem is that it tells every string is not periodic. I guess the problem is with the for loop in the isPeriodic function. Please help me get it correct.
import java.io.*;
import java.util.*;
public class Test {
/**
* #param args
*/
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader R = new java.io.BufferedReader
(new java.io.InputStreamReader(System.in));
//String st = R.readLine();
String st = "10101010";
if (isPeriodic(st) == false) {
System.out.println(" Non Periodic");
}
else {
System.out.println("Periodic");
}
}
private static boolean isPeriodic(String s)
{
String temp = s;
int i;
boolean pflag = false;
for ( i = 1; i <= (s.length()/2); i++) {
s = rotateNltr(s,i);
if (s == temp) {
pflag = true;
break;
}
}
return pflag;
}
private static String rotateNltr(String s, int n) {
if( n > s.length()) {
return null;
}
for ( int i = 0; i < n; i++) {
s = leftRotatebyOne(s);
}
//System.out.println(s);
return s;
}
private static String leftRotatebyOne(String s) {
char[] temp = s.toCharArray();
char t = temp[0];
for ( int i = 0 ; i < s.length()-1 ;i++ ) {
temp[i] = temp [i+1];
}
temp[s.length()-1] = t;
String r = new String(temp);
//System.out.println(r);
return r;
}
}
You can't compare objects (and that includes String's) with ==. You have to use the equals method.
Unlike C++ (which I assume is your language of preference) Java doesn't allow comparing String objects with the == operator. Use the equals method to compare the strings.
if (s.equals(temp)) {
pflag = true;
break;
}
In your isPeriodic() the check you are doing is wrong. Do it as below:
if (s.equals(temp)) {
pflag = true;
break;
}
s.equal(temp) alone wont solve the problem, yes it will make the code execute correctly for the input as given in Main method but for 1010, 1011 it wont.
Try using this method :
private static boolean isPeriodic(String s) {
String temp = s;
int i;
boolean pflag = false;
for (i = 1; i <= (s.length() / 2); i++) {
s = leftRotatebyOne(s);
if (s.equals(temp)) {
pflag = true;
break;
}
}
return pflag;
}
This will ensure that for all combination this program works.

How do I split strings in J2ME?

How do I split strings in J2ME in an effective way?
There is a StringTokenizer or String.split(String regex) in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).
There are a few implementations of a StringTokenizer class for J2ME. This one by Ostermiller will most likely include the functionality you need
See also this page on Mobile Programming Pit Stop for some modifications and the following example:
String firstToken;
StringTokenizer tok;
tok = new StringTokenizer("some|random|data","|");
firstToken= tok.nextToken();
There is no built in method to split strings. You have to write it on your own using
String.indexOf() and String.substring(). Not hard.
String.split(...) is available in J2SE, but not J2ME.
You are required to write your own algorithm: related post with sample solution.
I hope this one will help you... This is my own implementation i used in my application. Of course this can still be optimized. i just do not have time to do it... and also, I am working on StringBuffer here. Just refactor this to be able to use String instead.
public static String[] split(StringBuffer sb, String splitter){
String[] strs = new String[sb.length()];
int splitterLength = splitter.length();
int initialIndex = 0;
int indexOfSplitter = indexOf(sb, splitter, initialIndex);
int count = 0;
if(-1==indexOfSplitter) return new String[]{sb.toString()};
while(-1!=indexOfSplitter){
char[] chars = new char[indexOfSplitter-initialIndex];
sb.getChars(initialIndex, indexOfSplitter, chars, 0);
initialIndex = indexOfSplitter+splitterLength;
indexOfSplitter = indexOf(sb, splitter, indexOfSplitter+1);
strs[count] = new String(chars);
count++;
}
// get the remaining chars.
if(initialIndex+splitterLength<=sb.length()){
char[] chars = new char[sb.length()-initialIndex];
sb.getChars(initialIndex, sb.length(), chars, 0);
strs[count] = new String(chars);
count++;
}
String[] result = new String[count];
for(int i = 0; i<count; i++){
result[i] = strs[i];
}
return result;
}
public static int indexOf(StringBuffer sb, String str, int start){
int index = -1;
if((start>=sb.length() || start<-1) || str.length()<=0) return index;
char[] tofind = str.toCharArray();
outer: for(;start<sb.length(); start++){
char c = sb.charAt(start);
if(c==tofind[0]){
if(1==tofind.length) return start;
inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
char find = tofind[i];
int currentSourceIndex = start+i;
if(currentSourceIndex<sb.length()){
char source = sb.charAt(start+i);
if(find==source){
if(i==tofind.length-1){
return start;
}
continue inner;
} else {
start++;
continue outer;
}
} else {
return -1;
}
}
}
}
return index;
}
That depends on what exactly you want to achieve, but the function String.substring() will be in there somewhere:
String myString = "Hello World";
This will print the substring starting from index 6 to the end of the string:
System.out.println(myString.substring(6));
This will print the substring starting from index 0 until index 5:
System.out.println(myString.substring(0,5));
Output of all the code above:
World
Hello
Combine this with the other String functions (indexOf(). etc.) to achieve the desired effect!
Re-reading your question, it looks as though you may have been looking for String.split(). This will split your input string into an array of strings based on a given regex:
String myString = "Hi-There-Gang";
String[] splitStrings = myString.split("-");
This will result in the splitStrings array containing three string, "Hi", "There" and "Gang".
Re-reading your question again, String.split is not available in J2ME, but the same effect can be achieved with substring and indexOf.
public static Vector splitDelimiter(String text, char delimiter) {
Vector splittedString = null;
String text1 = "";
if (text != null) {
splittedString = new Vector();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == delimiter) {
splittedString.addElement(text1);
text1 = "";
} else {
text1 += text.charAt(i);
// if(i==text.length()-1){
// splittedString.addElement(text1);
// }
}
}
splittedString.addElement(text1);
}
return s
}
You can use this method for splitting a delimiter.
In J2ME no split, but you can use this code for split.This code works with only 1 simbol delimiter!!!
Use NetBeans.File\Create Project\ Java ME\ MobileApplication\Set project name(split)\Set checkmark.Delete all code in your (Midlet.java).Copy this code and past in your (Midlet.java).
//IDE NetBeans 7.3.1
//author: UserSuperPupsik
//email: usersuperpupsik#gmail.com
package split;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Vector;
public class Midlet extends MIDlet {
public String e1;
public Vector v=new Vector();
public int ma;
int IsD=0;
int vax=0;
public String out[];
private Form f;
public void split0(String text,String delimiter){
if (text!=""){
IsD=0;
int raz=0;
//v.removeAllElements();
v.setSize(0);
int io;
String temp="";
int ni=(text.length()-1);
for(io=0;io<=ni;io++){
char ch=text.charAt(io);
String st=""+ch;
if(io==0 && st.equals(delimiter)){IsD=1;}
if(!st.equals(delimiter)){temp=temp+st;} //Not equals (!=)
else if(st.equals(delimiter)&&temp!="")//equals (==)
{
IsD=1;
//f.append(temp);
v.addElement(temp);
temp="";
}
if(io==ni && temp!="") {
v.addElement(temp);
temp="";
}
if((io==ni)&&IsD==0&&temp!=""){v.addElement(temp);}
}
if(v.size()!=0){
ma=(v.size());
out=new String[ma];
v.copyInto(out);
}
//else if(v.size()==0){IsD=1; }
}
}
public void method1(){
f.append("\n");
f.append("IsD: " +IsD+"");
if (v.size()!=0){
for( vax=0;vax<=ma-1;vax++){
f.append("\n");
f.append(out[vax]);
}
}
}
public void startApp() {
f=new Form("Hello J2ME!");
Display.getDisplay(this).setCurrent(f);
f.append("");
split0("Hello.World.Good...Luck.end" , ".");
method1();
split0(".",".");
method1();
split0(" First WORD2 Word3 "," ");
method1();
split0("...",".");
method1();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Splited elements located in array called (out).For Example out[1]:Hello.
Good Luck!!!
Another alternative solution:
public static Vector split(String stringToSplit, String separator){
if(stringToSplit.length<1){
return null;
}
Vector stringsFound = new Vector();
String remainingString = stringToSplit;
while(remainingString.length()>0){
int separatorStartingIndex = remainingString.indexOf(separator);
if(separatorStartingIndex==-1){
// Not separators found in the remaining String. Get substring and finish
stringsFound.addElement(remainingString);
break;
}
else{
// The separator is at the beginning of the String,
// Push the beginning at the end of separator and continue
if(remainingString.startsWith(separator)){
remainingString = remainingString.substring(separator.length());
}
// The separator is present and is not the beginning, add substring and continue
else{
stringsFound.addElement(remainingString.substring(0, separatorStartingIndex));
remainingString = remainingString.substring(separatorStartingIndex + separator.length());
}
}
}
return stringsFound;
}

Categories