String reverse using Java'sstringbuilder - java

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());
}

Related

StringTokeniser not reading data

I've to read data from a file and I've just entered some sample data as a String in StringTokenizer. I can't understand what is wrong with my code here. Can someone please advise?
import java.util.StringTokenizer;
public class rough {
public static void main(String[] args) throws Exception {
StringTokenizer itr = new StringTokenizer("PKE2324 02-12-2020 200"
+ "\nMJD432 19-05-2019 150");
while (itr.hasMoreTokens()){
String line = itr.nextToken().toString();
String[] tokens = line.split(" ");
String[] date = tokens[1].split("-");
String yr = date[2];
String reg = tokens[0];
String regy = new String(reg + " " + yr);
System.out.println(regy);
}
}
}
I want to get the registration number and year as a String. When I run this, I keep getting ArrayIndexOutofBounds
This is the type of runtime error which has been caused due to logical error and inappropriate delimeter.
Assuming you want to tokenise the big string using newline character, use, \n as delimeter to StringTokenizer.
Have a look at the corrected code below which satisfies your use case:
import java.util.StringTokenizer;
public class rough {
public static void main(String[] args) throws Exception {
StringTokenizer itr = new StringTokenizer("PKE2324 02-12-2020 200"
+ "\nMJD432 19-05-2019 150", "\n");
while (itr.hasMoreTokens()){
String line = itr.nextToken().toString();
String[] tokens = line.split(" ");
String[] date = tokens[1].split("-");
String yr = date[2];
String reg = tokens[0];
String regy = new String(reg + " " + yr);
System.out.println(regy);
}
}
}
Output:
PKE2324 2020
MJD432 2019
Exception caused by this line
String[] tokens = line.split(" ");
String[] date = tokens[1].split("-");
line = PKE2324, so tokens[] = { "PKE2324" } --> length = 1
tokens[1] --> ArrayIndexOutOfBoundException
To fix this:
StringTokenizer itr = new StringTokenizer("PKE2324 02-12-2020 200"
+ "\nMJD432 19-05-2019 150");
Default delimeter is whitespace.
You should pass delimeter in constructor if you want different delimeter.

Parse hashtags between symbols

I need to parse hashtags from String (test comment #georgios#gsabanti sefse #afa).
String text = "test comment #georgios#gsabanti sefse #afa";
String[] words = text.split(" ");
List<String> tags = new ArrayList<String>();
for ( final String word : words) {
if (word.substring(0, 1).equals("#")) {
tags.add(word);
}
}
In the end i need an Array with "#georgios" , "#gsabanti" , "#afa" elements.
But now #georgios#gsabanti showing like one hashtag.
How to fix it?
+1 for the Regular Expressions:
Matcher matcher = Pattern.compile("(#[^#\\s]*)")
.matcher("test comment #georgios#gsabanti sefse #afa");
List<String> tags = new ArrayList<>();
while (matcher.find()) {
tags.add(matcher.group());
}
System.out.println(tags);
Here is a simple way of doing that
String text = "test comment #georgios#gsabanti sefse #afa";
String patternst = "#[a-zA-Z0-9]*";
Pattern pattern = Pattern.compile(patternst);
Matcher matcher = pattern.matcher(text);
List<String> tags = new ArrayList<String>();
while (matcher.find()) {
tags.add(matcher.group(0));
}
I hope it will work for you :)
Use Arraylist instead of array:
String text = "test comment #georgios#gsabanti sefse #afa";
ArrayList<String> hashTags = new ArrayList()<>;
char[] c = text.toCharArray();
for(int i=0;i<c.length;i++) {
if(c[i]=='#') {
String hash = "";
for(int j=i+1;j<c.length;j++) {
if(c[j]==' ' || c[j]=='#') {
hashTags.add(hash);
hash="";
break;
}
hash+=c[j];
}
}
}
String text = "test comment #georgios#gsabanti sefse #afa";
String[] words = text.split("(?=#)|\\s+")
List<String> tags = new ArrayList<String>();
for ( final String word : words) {
if (!word.isEmpty() && word.startsWith("#")) {
tags.add(word);
}
}
You can split your string at " " or "#" and keep the delimiters and filter those out which start with "#" like below:
public static void main(String[] args){
String text = "test comment #georgios#gsabanti sefse #afa";
String[] tags = Stream.of(text.split("(?=#)|(?= )")).filter(e->e.startsWith("#")).toArray(String[]::new);
System.out.println(Arrays.toString(tags));
}

How can i split String in java with custom pattern

I am trying to get the location data from this string using String.split("[,\\:]");
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
String[] str = location.split("[,\\:]");
How can i get the data like this.
str[0] = 27.980194
str[1] = 46.090199
str[2] = 0.48
str[3] = 1
str[4] = 6
Thank you for any help!
If you just want to keep the numbers (including dot separator), you can use:
String[] str = location.split("[^\\d\\.]+");
You will need to ignore the first element in the array which is an empty string.
That will only work if the data names don't contain numbers or dots.
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
Matcher m = Pattern.compile( "\\d+\\.*\\d*" ).matcher(location);
List<String> allMatches = new ArrayList<>();
while (m.find( )) {
allMatches.add(m.group());
}
System.out.println(allMatches);
Quick and Dirty:
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
List<String> strList = (List) Arrays.asList( location.split("[,\\:]"));
String[] str = new String[5];
int count=0;
for(String s : strList){
try {
Double d =Double.parseDouble(s);
str[count] = d.toString();
System.out.println("In String Array:"+str[count]);
count++;
} catch (NumberFormatException e) {
System.out.println("s:"+s);
}
}

String Tokenizer separation

I want to know how can we separate words of a sentence where delimiter is be a ' '(space) or '?'
or '.'.
For ex
Input: THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS.
Output:
THIS
IS
A
STRING
PROGRAM
IS
THIS
EASY
YES
IT
IS
Refer to the constructor of the StringTokenizer class in Java. It has provision to accept custom delimiter.
Try this:
StringTokenizer tokenizer = new StringTokenizer("THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS", " .?");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextElement());
}
public static void main(String[] args) {
String str = "THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by space ------");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}

Save for loop result as string

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

Categories