How can I bring text by StringTokenizer - java

Imagine this array.
data[0] = Marine
data[1] = Medic
data[2] = Firebat
I want to bring attribute of code (002530, 068270, 053800) to code[] array.
and pure text (Marine, Medic, Firebat).
Like this:
code[0] = 002530
code[1] = 068270
code[2] = 053800
text[0] = Marine
text[1] = Medic
text[2] = Firebat
How can I do that? Should I have to use StringTokenizer? or split()?
I don't know how to get that. Please Help me. Thank you.

You can use regular expressions, See this Voguella tutorial
".*code=([0-9]*).*>([A-Za-z]*)<.*"
And a code like this:
String[] array = new String[3];
array[0] = "Marine";
array[1] = "Medic";
array[2] = "Firebat";
Pattern pattern = Pattern.compile(".*code=([0-9]*).*>([A-Za-z]*)<.*");
for (int i = 0; i < array.length; i++) {
String string = array[i];
Matcher ma = pattern.matcher(string);
System.out.println("Code " + i + ":" + ma.replaceFirst("$1"));
System.out.println("Text " + i + ":" + ma.replaceFirst("$2"));
}
see a working example in: http://ideone.com/WJIjM5
Obs: remember to escape " in your strings.

Related

Sorting arrayList from resultset

I'm working on a project that involves 2 separate db to generate the report. The result of one is passed into the other query and a final report is generated. Now, i wan to sort the final report but having issues with it. Java constructor for "java.util.Arrays" with arguments "" not found.
var fist = new java.util.Arrays();
var list = new java.util.ArrayList();
var gist = new java.util.ArrayList();
var arr = '';
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('Postgres connection');
var result3 = dbConn.executeCachedQuery(...)
while (result3.next()) {
var value1 = result3.getString(1);
var value2 = result3.getString(2);
var dbConn3 = DatabaseConnectionFactory.createDatabaseConnection('Oracle connection'));
var result2 = dbConn3.executeCachedQuery("SELECT name FROM producer WHERE send = '" + value1 + "' AND code = '" + value2 + "' ORDER BY name")
while (result2.next()) {
var sending = result2.getString(1);
}
dbConn3.close();
if (sending != undefined) {
arr += gist.add(sending);
arr += gist.add(value1);
arr += gist.add(value2);
arr += gist.add(result3.getString(3));
fist.add(arr);
}
}
Arrays.sort(fist); //i'm thinking this should sort it before displaying it
while (fist.next()) {
xmlMs += "<tr>"
xmlMs += "<td>" + sending + "</td>";
xmlMs += "<td>" + value1 + "</td>";
xmlMs += "<td>" + value2 + "</td>";
xmlMs += "<td align='center'>" + result3.getString(3) + "</td>";
xmlMs += "</tr>";
}
Well yes, your compiler is telling you that var fist = new java.util.Arrays(); is invalid, java.util.Arrays doesn't provide a public no-args constructor. Did you by chance mean ArrayList instead of Arrays?
Arrays doesn't have a constructor defined in the source code, so new Arrays(); causes the compiler to scream at you.
If you want an array of something you use
type[] varname = new type[size];
Note that the [] is what makes it an Array.
Ex:
int[] x = new int[5];
That will hold an array of 5 ints.

Add Array elements to String

I'm creating a game of hangman, and long story short, is there a shortcut of sorts to put this array of separate strings together into a string other than doing like below?
String after = under[0] + under[1] + under[2] + under[3] + under[4] + under[5] + under[6] + under[7] + under[8] + under[9] + under[10] + under[11] + under[12] + under[13] + under[14] + under[15] + under[16] + under[17] + under[18] + under[19] + under[20] + under[21];
You can do it with a loop, like this:
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i != 22 ; i++) {
sb.append(under[i]);
}
String after = sb.toString();
You can also add strings to an initially empty string, but that's suboptimal, because all the intermediate strings get allocated and released in a loop.
Always use loop to perform repetitive operation like this.
Also, It is advised to use StringBuilder instead of String. String in JAVA is immutable.
StringBuilder sb = new StringBuilder();
int nCount = 22;
for (int iCnt = 0 ; iCnt <= nCount ; iCnt++) {
sb.append(under[iCnt]);
}
String after = sb.toString();
try it:
String after = "";
for (int i=0; i<22; i++)
after += under[i];
This code is not shorter, but is less tedious:
StringBuilder afterBldr = new StringBuilder();
for (String underEl : under) {
afterBldr.append(underEl);
}
String after = afterBldr.toString();
Apache Joiner can be used here.
Joiner.on("").join(names)
If you have access to the Apache Commons library, use the join() method, it's the nicest solution:
String str = StringUtils.join(under, "");

Get the Beginning Position Of a field

Hi Guys I am writing a code that reads a text file in this format:
City |First Name| Second Name|Last Name|
The output I currently have is :
Column 1 is 17--------City
Column 2 is 10--------First Name
Column 3 is 12--------Second Name
Column 4 is 9---------Last Name
I need the Begin Position Also Of each Field in the Text File for example:
Column 1 is 17--------City : Position 1
Column 2 is 10--------First Name: Position 18
Column 3 is 12--------Second Name: Position 31
Column 4 is 9---------Last Name: Position 44
Here Is the Code I currently Have. Is there a way to achieve This?
package stanley.column.reader;
import java.io.*;
public class StanleyColumnReader {
public static void main(String[] args) throws IOException {
System.out.println("Developed By Stanley Mungai");
File f = new File("C:/File/");
if (!f.exists()) {
f.createNewFile();
} else {
f.delete();
}
String [] files = f.list();
for (int j = 0; j < files.length; j++){
FileInputStream fs = new FileInputStream("C:/File/" + files[j]);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String result = "_result";
BufferedWriter is = new BufferedWriter(new FileWriter("C:/File/" + files[j] + result + ".txt"));
for (int i = 0; i < 0; i++) {
br.readLine();
}
String line = br.readLine();
String[] split = line.split("|");
for (int i = 0; i < split.length; i++) {
int k = i + 1;
System.out.println("Calculating the size of field " + k );
is.write("Column " + k + " is " + split[i].length());
is.flush();
is.newLine();
}
}
System.out.println("Success");
System.out.println("Output Saved to C:/File");
}
}
You could do that with a bit more advanced regexp group matching and get the group start index. But might be overkill and too advanced considering the question.
But a quick simple way in your case that might work is to just use indexOf on the line.
That is change your output to include:
" Position "+(line.indexOf(split[i])+1)
As long as a last name, first name and city aren't repeated on the same line...
You hardly need to flush on each line by the way, I suggest to move it outside the loop.
The regexp solution:
//first declare the pattern once in the class
static final Pattern pattern = Pattern.compile("\\s*(.*?)\\s*\\|");
...
//instead of the split loop:
String line = "City |First Name| Second Name|Last Name| Foo |Bar |"; //br.readLine();
Matcher matcher = pattern.matcher(line);
int column = 1;
while (matcher.find(column == 1 ? 0 : matcher.end())) {
String match = matcher.group(1);
System.out.println("Column " + column + " is " + match.length() + "---" + match + ": Position " + (matcher.start() + 1));
column++;
}
Possibly, depending on the exact position you want, you might want to change (matcher.start()+1) to (matcher.start(1)+1)
IS this an assignment? Please tag it properly.
You haven't said whether the delimiters are "|" in the data too but seeing your code, I am assuming it is.
What I don't understand is how the position you mentioned for Column 3 is 31 and column 4 is 44? Column 3 should be 10+17+1 =28 and column 4 should be 10+17+12+1=40. If I am getting it wrong, you need to post your original data too.
String[] split = line.split("|");
int pos=1; //initial position
for (int i = 0; i < split.length; i++) {
System.out.println("Calculating the size of field " + (i+1));
is.write("Column " + (i+1) + " is " + pos+" : Position "+pos);
pos=pos+split[i].length+1; //starting position for next column data
is.flush();
is.newLine();
}
Or you could find position by using indexOf method : line.indexOf(split[i])+1
If I understand what you need. Maybe you can use the indexOf method. This brings you the first coincidence. After finding this, change the pipe for something different and call indexOf pipe in the next iteration again.
String line = br.readLine();
for (int i = 0; i < split.length; i++) {
System.out.println("Calculating the position " + line.indexOf("|") );
line[line.indexOf("|")] = ",";
}

Words inside square brackes - RegExp

String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}
I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]
Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N

Java special characters RegEx

I want to achieve following using Regular expression in Java
String[] paramsToReplace = {"email", "address", "phone"};
//input URL string
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
//output URL string
String op = "http://www.google.com?name=bob&email=&address=&phone=";
The URL can contain special characters like %
Try this expression: (email=)[^&]+ (replace email with your array elements) and replace with the group: input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");
String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
String output = input;
for( String param : paramsToReplace ) {
output = output.replaceAll("("+ param + "=)[^&]+", "$1");
}
For the example above. you can use split
String[] temp = ip.split("?name=")[1].split("&")[0];
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone=";
Something like this?
private final static String REPLACE_REGEX = "=.+\\&";
ip=ip+"&";
for(String param : paramsToReplace) {
ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&"));
}
P.S. This is only a concept, i didn't compile this code.
You don't need regular expressions to achieve that:
String op = ip;
for (String param : paramsToReplace) {
int start = op.indexOf("?" + param);
if (start < 0)
start = op.indexOf("&" + param);
if (start < 0)
continue;
int end = op.indexOf("&", start + 1);
if (end < 0)
end = op.length();
op = op.substring(0, start + param.length() + 2) + op.substring(end);
}

Categories

Resources