Java - split string into an array - java

I have this code
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split(" ");
System.out.println(string_array.length);
and it returns the value of 1 when I run it. Why is that? It seems as if only the first word of the string gets saved.

Use \\s and update the code as below
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split("\\s");
System.out.println(string_array.length);

Most probably what you think is space (ASCII decimal 32) is not (in your input string).
That would explain perfectly the behavior you're seeing.

Related

Java - How to display all substrings in String without using an array

I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan

How to escape special characters from JSON when assign it to Java String

im tring to assign value from json to java String. but JSON value is including some special charactor ("\"). when i was try to assigen it to the string it gives error.
this is the JSON value,
"ValueDate":"\/Date(1440959400000+0530)\/"
this is how i trying to use it.
HistoryVO.setValueDate(DataUtil.getDateForUnixDate(historyJson.getString("ValueDate")));
or
Given that
I want ... to get [the] Date(1440959400000+0530) part,
I would use
String value = "/Date(1440959400000+0530)/";
int pos1 = value.indexOf("Date(");
if (pos1 > -1) {
int pos2 = value.indexOf(")", pos1);
if (pos2 > pos1) {
value = value.substring(pos1, pos2 + 1);
System.out.println(value);
}
}
Output is
Date(1440959400000+0530)
Note: This works by looking for "Date(" and then the next ")", and it removes everything not between those two patterns.
If you have specific character, ( and ), use substring method to get the value.
String value = "\\/Date(1440959400000+0530)\\/";
int start = value.indexOf("(");
int last = value.lastIndexOf("0");
value = value.substring(start + 1, last + 1);
System.out.println(value); <--- 1440959400000+0530
DataUtil.getDateForUnixDate(value);
I don't know DataUtil.getDateForUnixDate() method, but take care of + character because of it is not number string.
Update
To remove / character use replace method.
String value = "/Date(1440959400000+0530)/";
value = value.replace("/", "");
System.out.println(value);
output
Date(1440959400000+0530)
Mac,
As you asked for something like
String ValueDate = "\/Date(1440959400000+0530)\/";
The above one is not possible in java string, As it shows as invalid escape sequence, So replace the slash '\' as double slash '\' as below,
String ValueDate = "\\/Date(1440959400000+0530)\\/";
If am not clear of our question, pls describe it clearly
Regards,
Hari
i found the answer for my own question.
historyJson.getString("ValueDate");
this return the String like /Date(1440959400000+0530)/
now i can split it. thank you all for the help.
regards, macdaddy

string index out of range exception

I'm looking for help correcting an exception error for 'string index out of range'. My code is supposed to take two strings as input from the user(string1 and string2) and create new strings that are parts of the originals.
So far I have the following:
modString1 = string1.substring(string1.length() -3, string1.length());
modString2 = string2.substring(0,3);
The above code is supposed to take the last 3 characters of string1 and the first 3 characters of string2. The problem I am having comes when the user inputs a string that is shorter than 3 characters.
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
For example, if the user enters 'A' for the first string it will change the string to 'xxA' and if 'A' is entered for the second string it will change that to 'Axx'?
Put an if statement before your code, checking the length of the string before you process it.
For example:
if(string1.length() < 3) {
// Add characters to the string
}
I'm wondering if there is a way to check the input and add a character (x for example) if the string is too short?
What you are looking for is called padding.
It can be done in a number of ways. The simplest is probably to use an external library such as Apache's StringUtils. You could also write a padding method yourself using a StringBuilder.
Related:
How can I pad a String in Java?
put the validation like below and add the string.
For ex.
if(string1.length()<3){
String op = 'xx';
string1 += op;
}

Split a string by "," and not spaces

Every time I try to split a string e.g. foo,bar,foo bar,bar it skips the string after the space.
How do I stop Java from doing this?
String[] transactionItem = transactionItems[i].split(",");
if transactioItems[0] = Y685,Blue Tie,2,34.79,2
it would output
transactionItem[0] = Y685
transactionItem[1] = Blue
transactionItem[3] = out of bounds
This code is working correctly:
String[] split = myString.split(",");
Basic demo : http://www.ideone.com/kLchx
With your new example, it works too : http://www.ideone.com/hWWzd
I think we need more code to search the problem.
This:
transactionItem[3]
Should be 2 instead of 3. Arrays are 0 indexed.

Java Searching Through a String

So I want to search through a string to see if it contains the substring that I'm looking for. This is the algorithm I wrote up:
//Declares the String to be searched
String temp = "Hello World?";
//A String array is created to store the individual
//substrings in temp
String[] array = temp.split(" ");
//Iterates through String array and determines if the
//substring is present
for(String a : array)
{
if(a.equalsIgnoreCase("hello"))
{
System.out.println("Found");
break;
}
System.out.println("Not Found");
}
This algorithm works for "hello" but I don't know how to get it to work for "world" since it has a question mark attached to it.
Thanks for any help!
Take a look:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence)
String.contains();
To get a containsIgnoreCase(), you'll have to make your searchword and your String toLowerCase().
Take a look at this answer:
How to check if a String contains another String in a case insensitive manner in Java?
return s1.toLowerCase().contains(s2.toLowerCase());
This will also be true for:
war of the worlds, because it will find world. If you don't want this behavior, youll have to change your method like #Bart Kiers said.
Split on the following instead:
"[\\s?.!,]"
which matches any space char, question mark, dot, exclamation or a comma (add more chars if you like).
Or do a temp = temp.toLowerCase() and then temp.contains("world").
You dont have to do this, it's already implemented:
IndexOf and others
You may want to use :
String string = "Hello World?";
boolean b = string.indexOf("Hello") > 0; // true
To ignore case, regular expressions must be used .
b = string.matches("(?i).*Hello.*");
One more variation to ignore case would be :
// To ignore case
b=string.toLowerCase().indexOf("Hello".toLowerCase()) > 0 // true

Categories