Save for loop result as string - java

String input[] = request.getParameterValues("checkbox");
for(int i=0;i<input.length;i++) {
if (i==input.length-1) {
System.out.print(input[i]+" ");
} else {
System.out.print(input[i]+", ");
}
}
The result is that i print to console something like "CustomerId, FirstName, LastName, Phone".
I want to save the result of the for loop as a string variable instead, so then i can do
String query = "select "+result above+" from table";
How to do it?

You keep appending into a StringBuilder and then convert it to String
StringBuilder sb = new StringBuilder();
for(int i=0;i<input.length;i++) {
if (i==input.length-1) {
System.out.print(input[i]+" ");
sb = sb.concat(input[i] + ",");
} else {
System.out.print(input[i]+", ");
sb = sb.concat(input[i] + ",");
}
}
Then,
String query = "select "+sb.toString()+" from table";

Use a StringBuilder to concatenate strings together. (it is technically possible to use String objects, and concatenate them together using the + operator, but that has a lot of downsides...)
String input[] = request.getParameterValues("checkbox");
StringBuilder sb = new StringBuilder(); // create empty StringBuilder instance
for(int i=0;i<input.length;i++) {
sb.append(input[i]); //append element
if (i==input.length-1) {
sb.append(" "); //append space
} else {
sb.append(", "); //append comma
}
}
String result = sb.toString();
Systemout.println(result);
Or you could build (see Builder pattern) the whole query using a StringBuilder object, with methods for each part ( addFields(StringBuilder sb), addFromPart(StringBuilder sb), addWhereClause(StringBuilder sb)), and voila, you have the insides of a small data access framework...
public abstract class MyQueryBuilder {
protected abstract void addFields(StringBuilder sb);
protected abstract void addFromPart(StringBuilder sb);
protected abstract void addWhereClause(StringBuilder sb);
public final String getQuery() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
addFields(sb); //this adds the fields to be selected
sb.append(" FROM ");
addFromPart(sb); //this adds the tables in the FROM clause
addWhereClause(sb); //this adds the where clause
//...etc
return sb.toString();
}
}

You can do this using a StringBuilder instead of printing the values out.
String input[] = request.getParameterValues("checkbox");
StringBuilder builder = new StringBuilder();
for(int i=0;i<input.length;i++) {
if (i==input.length-1) {
builder.append(input[i]+" ");
} else {
builder.append(input[i]+", ");
}
}
Regards,
kayz

Related

display array issues possibly due to whitespace characters

I'm trying to import a txt file with car info and separate the strings into arrays and then display them. The number of doors is combined with the next number plate. Have tried a few ways to get rid of the whitespace characters which I think is causing the issue but have had no luck.
whitespace chars
My code displays this result:
Number Plate : AG53DBO
Car Type : Mercedes
Engine Size : 1000
Colour : (255:0:0)
No. of Doors : 4
MD17WBW
Number Plate : 4
MD17WBW
Car Type : Volkswagen
Engine Size : 2300
Colour : (0:0:255)
No. of Doors : 5
ED03HSH
Code:
public class Application {
public static void main(String[] args) throws IOException {
///// ---- Import File ---- /////
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
String content = stringBuilder.toString();
///// ---- Split file into array ---- /////
String[] dataList = content.split(",");
// Display array
for (String temp : dataList) {
// System.out.println(temp);
}
ArrayList<Car> carArray = new ArrayList();
// Loop variables
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 5) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
}
}
And
public class Car {
String[] data;
private String modelUnpro;
private String engineSizeUnpro;
private String registrationUnpro;
private String colourUnpro;
private String doorNoUnpro;
// Constructor
public Car(String[] data, int arrayPosition) {
registrationUnpro = data[arrayPosition];
modelUnpro = data[arrayPosition + 1];
engineSizeUnpro = data[arrayPosition + 2];
colourUnpro = data[arrayPosition + 3];
doorNoUnpro = data[arrayPosition + 4];
}
// Getters
private String getModelUnpro() {
return modelUnpro;
}
private String getEngineSizeUnpro() {
return engineSizeUnpro;
}
private String getRegistrationUnpro() {
return registrationUnpro;
}
private String getColourUnpro() {
return colourUnpro;
}
private String getDoorNoUnpro() {
return doorNoUnpro;
}
public String displayCar() {
return "Number Plate : " + getRegistrationUnpro() + "\n Car Type : " + getModelUnpro() + "\n Engine Size : "
+ getEngineSizeUnpro() + "\n Colour : " + getColourUnpro() + "\n No. of Doors : " + getDoorNoUnpro() + "\n";
}
}
Text file:
AG53DBO,Mercedes,1000,(255:0:0),4
MD17WBW,Volkswagen,2300,(0:0:255),5
ED03HSH,Toyota,2000,(0:0:255),4
OH01AYO,Honda,1300,(0:255:0),3
WE07CND,Nissan,2000,(0:255:0),3
NF02FMC,Mercedes,1200,(0:0:255),5
PM16DNO,Volkswagen,1300,(255:0:0),5
MA53OKB,Honda,1400,(0:0:0),4
VV64BHH,Honda,1600,(0:0:255),5
ER53EVW,Ford,2000,(0:0:255),3
Remove Line separator from while loop.
String fileName = "D:\\Files\\a.txt";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line.trim());
}
reader.close();
String content = stringBuilder.toString();
String[] dataList = content.split(",");
ArrayList<Car> carArray = new ArrayList();
int listLength = 1;
int arrayPosition = 0;
// (dataList.length/5)
while (listLength < 3) {
Car y = new Car(dataList, arrayPosition);
carArray.add(y);
listLength++;
arrayPosition += 4;
}
for (Car temp : carArray) {
System.out.println(temp.displayCar());
}
In StringBuilder you collect all lines:
AG53DBO,Mercedes,1000,(255:0:0),4\r\nMD17WBW,Volkswagen,2300,(0:0:255),5\r\n...
This string should first be spit on ls - and then you have lines with fields separated by comma.
Now just splitting by comma will cause a doubled array element 4\r\nMD17WBW.
Something like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path); // Without line ending.
List<Car> cars = new ArrayList<>();
for (String line : lines) {
String[] data = line.split(",");
Car car = new Car(data);
cars.add(car);
}
Path, Paths and especially Files are very handy classes. With java Streams one also can abbreviate things like:
String fileName =
"C:\\Users\\beng\\eclipse-workspace\\Assignment Trailblazer\\Car Data";
Path path = Paths.get(fileName);
List<Car> cars = Files.lines(path) // Stream<String>
.map(line -> line.split(",")) // Stream<String[]>
.map(Car::new) // Stream<Car>
.collect(Collectors.toList()); // List<Car>
Here .lines returns a Stream<String> (walking cursor) of lines in the file, without line separator.
Then .map(l -> l.split(",")) splits every line.
Then the Car(String[]) constructor is called on the string array.
Then the result is collected in a List.

String reverse using Java'sstringbuilder

I develop using Java to make a little project.
I want String reverse.
If I entered "I am a girl", Printed reversing...
Already I tried to use StringBuilder.
Also I write it using StringBuffer grammar...
But I failed...
It is not printed my wish...
WISH
My with Print -> "I ma a lrig"
"I am a girl" -> "I ma a lrig" REVERSE!!
How can I do?..
Please help me thank you~!!!
public String reverse() {
String[] words = str.split("\\s");
StringTokenizer stringTokenizer = new StringTokenizer(str, " ");
for (String string : words) {
System.out.print(string);
}
String a = Arrays.toString(words);
StringBuilder builder = new StringBuilder(a);
System.out.println(words[0]);
for (String st : words){
System.out.print(st);
}
return "";
}
Java 8 code to do this :
public static void main(String[] args) {
String str = "I am a girl";
StringBuilder sb = new StringBuilder();
// split() returns an array of Strings, for each string, append it to a StringBuilder by adding a space.
Arrays.asList(str.split("\\s+")).stream().forEach(s -> {
sb.append(new StringBuilder(s).reverse() + " ");
});
String reversed = sb.toString().trim(); // remove trailing space
System.out.println(reversed);
}
O/P :
I ma a lrig
if you do not want to go with lambda then you can try this solution too
String str = "I am a girl";
String finalString = "";
String s[] = str.split(" ");
for (String st : s) {
finalString += new StringBuilder(st).reverse().append(" ").toString();
}
System.out.println(finalString.trim());
}

extract multiples same string from a string

I need to split a String by a specific String which can be placed anywhere (there can be multiple occurences of this string at same time) and reconstruct the entire string by adding extracts into something like a StringBuffer. The case of the specific String to seek must be insensitive
For example:
String targeted = "test" ;
String plainString ="azertytestqwerty";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("azerty");
sb.append("test");
sb.append("qwerty");
--------------------------
String targeted = "test" ;
String plainString ="a.test";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("a.");
sb.append("test");
--------------------------
String targeted = "test" ;
String plainString ="test mlm";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("test");
sb.append("mlm");
--------------------------
String targeted = "test" ;
String plainString ="aaatestzzztest";
//desired outcome
StringBuffer sb = new StringBuffer();
sb.append("aaa");
sb.append("test");
sb.append("zzz");
sb.append("test");
Any simple way to do this?
I think I need to use a regex like:
Pattern pattern = Pattern.compile(".*"+targeted +".*");
Matcher matcher = pattern.matcher(text);
if (matcher.find())
{
System.out.println(matcher.group(1));
}
But then I don't know how to extract the strings and add them in same order
The reason why I do this it's because the plainString will be added into a Excel cell using POI but I need to add font color for the targeted string.
Example:
XSSFRichTextString richString = new XSSFRichTextString();
richString.append("azerty");
richString.append("test", highlightFont);
richString.append("qwerty");
cell.setCellValue(richString);
Thank you very much
Here is the method, you can try any combination.
public String extractMultiples(String plainString, String targeted) {
StringBuffer sb = new StringBuffer();
// split covers all occurrences in the beginning;empty element, and in
// the middle
String[] result = plainString.split(targeted);
for (int i = 0; i < result.length; i++) {
sb.append(result[i]);
if (i < result.length - 1)// not the last one
sb.append(targeted);
}
// in the end
if (plainString.endsWith(targeted))
sb.append(targeted);
return sb.toString();
}
Pattern and Matcher are maybe a little bit too much...
just do a split on the word and then make a for loop over the resulting array...
Example
public static void main(String[] args) {
String targeted = "test";
String plainString = "azertytestqwerty";
String[] result = plainString.split(targeted);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(result[i]);
}
}

Reverse every word in a string and capitalize the start of the word

Sample input:
abc def ghi
Sample output:
Cba Fed Ihg
This is my code:
import java.util.Stack;
public class StringRev {
static String output1 = new String();
static Stack<Character> stack = new Stack<Character>();
public static void ReverseString(String input) {
input = input + " ";
for (int i = 0; i < input.length(); i++) {
boolean cap = true;
if (input.charAt(i) == ' ') {
while (!stack.isEmpty()) {
if (cap) {
char c = stack.pop().charValue();
c = Character.toUpperCase(c);
output1 = output1 + c;
cap = false;
} else
output1 = output1 + stack.pop().charValue();
}
output1 += " ";
} else {
stack.push(input.charAt(i));
}
}
System.out.print(output1);
}
}
Any better solutions?
Make use of
StringBuilder#reverse()
Then without adding any third party libraries,
String originalString = "abc def ghi";
StringBuilder resultBuilder = new StringBuilder();
for (String string : originalString.split(" ")) {
String revStr = new StringBuilder(string).reverse().toString();
revStr = Character.toUpperCase(revStr.charAt(0))
+ revStr.substring(1);
resultBuilder.append(revStr).append(" ");
}
System.out.println(resultBuilder.toString()); //Cba Fed Ihg
Have a Demo
You can use the StringBuffer to reverse() a string.
And then use the WordUtils#capitalize(String) method to make first letter of the string capitalized.
String str = "abc def ghi";
StringBuilder sb = new StringBuilder();
for (String s : str.split(" ")) {
String revStr = new StringBuffer(s).reverse().toString();
sb.append(WordUtils.capitalize(revStr)).append(" ");
}
String strReversed = sb.toString();
public static String reverseString(final String input){
if(null == input || isEmpty(input))
return "";
String result = "";
String[] items = input.split(" ");
for(int i = 0; i < items.length; i++){
result += new StringBuffer(items[i]).reverse().toString();
}
return result.substring(0,1).toupperCase() + result.substring(1);
}
1) Reverse the String with this
StringBuffer a = new StringBuffer("Java");
a.reverse();
2) To make First letter capital use
StringUtils class in apache commons lang package org.apache.commons.lang.StringUtils
It makes first letter capital
capitalise(String);
Hope it helps.
Edited
Reverse the string first and make the first character to uppercase
String string="hello jump";
StringTokenizer str = new StringTokenizer(string," ") ;
String finalString ;
while (str.hasMoreTokens()) {
String input = str.nextToken() ;
String reverse = new StringBuffer(input).reverse().toString();
System.out.println(reverse);
String output = reverse .substring(0, 1).toUpperCase() + reverse .substring(1);
finalString=finalString+" "+output ;
}
System.out.println(finalString);
import java.util.*;
public class CapatiliseAndReverse {
public static void reverseCharacter(String input) {
String result = "";
StringBuilder revString = null;
String split[] = input.split(" ");
for (int i = 0; i < split.length; i++) {
revString = new StringBuilder(split[i]);
revString = revString.reverse();
for (int index = 0; index < revString.length(); index++) {
char c = revString.charAt(index);
if (Character.isLowerCase(revString.charAt(0))) {
revString.setCharAt(0, Character.toUpperCase(c));
}
if (Character.isUpperCase(c)) {
revString.setCharAt(index, Character.toLowerCase(c));
}
}
result = result + " " + revString;
}
System.out.println(result.trim());
}
public static void main(String[] args) {
//System.out.println(reverseCharacter("old is GlOd"));
Scanner sc = new Scanner(System.in);
reverseCharacter(sc.nextLine());
}
}

convert List<String> to a static string if possible

I am trying to wrap my head around List<String> I have a dynamicly created array List<String> selected_tags That I would like to convert to break apart the elements and place a "%" inbetween each element so I can use the new string in a http call.
Creat my new List :
public List<String> selected_tags = new ArrayList<String>();
Fill my List string
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
I then need to use selected_tags in my url
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags="+ BROKEN DOWN LIST<STRING>);
I would like for it to look like
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags=tag1%tag2%tag3);
StringBuilder s = new StringBuilder();
boolean first = true;
for (String tag : selected_tags) {
if (!first)
s.append("%");
else
first = false;
s.append(tag);
}
String myUrlString = "tags=" + s.toString();
actually, you should have something like
StringBuilder sb = new StringBuilder();
if(selected_tags.size() > 0) {
sb.append(selected_tags.get(0);
for(int i = 1 ; i < selected_tags.size(); i++) {
sb.append("%");
sb.append(selected_tags.get(i));
}
}
return sb.toString();
StringBuilder result = new StringBuilder();
String prepend = "tags=";
for( String tag : selected_tags ){
result.append(prepend).append(tag);
prepend = "%";
}
String resultString = result.toString();
StringBuilder sb = new StringBuilder();
for (String tag : selected_tags) {
sb.append("%").append(tag);
}
sb.replace(0,1,"tags=");

Categories