how to recover an element of a String - java

I have a string of the form:
str = "word1_word2_word3_word4_word5"
and I want to retrieve each keyword in a separate variable with the help of "_" how separator.
example: str = "hello_how_are_you_?"
for str1=hello, str2=how, str3=are, str4=you and str4=?
thank for your help and sorry for my school english.

String str = "hello_how_are_you_?"
String[] words = str.split("_");
Output:
words[0]; // hello
words[1]; // how
words[2]; // are
words[3]; // you
words[4]; // ?

Try:
String str = "hello_how_are_you_?";
String item[]=str.split("_")

Just use split for it.
/* String to split. */
String str = "one-two-three";
String[] temp;
/* delimiter */
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);

String phrase = "hello_how_are_you_?";
String[] tokens = phrase.split("_");
for( String str: tokens)
System.out.println(str);
This code will print this on the screen:
hello
how
are
you
?
Anyway, if you are trying to make something Paraclete there should be a better way to do it then saving data in strings like that.
Here is a tutorial in case you need something more complex then split by a single character: http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html

String str="hello_how_are_you_?";
String[] strSplit=str.split("_");

Related

delete dynamic character from string

I have a string containing numbers separated with ,. I want to remove the , before the first character.
The input is ,1,2,3,4,5,6,7,8,9,10, and this code does not work:
results.replaceFirst(",","");
Strings are immutable in Java. Calling a method on a string will not modify the string itself, but will instead return a new string.
In order to capture this new string, you need to assign the result of the operation back to a variable:
results = results.replaceFirst(",", "");
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
str = str .startsWith(",") ? str .substring(1) : str ;
System.out.println("output"+str); // 1,2,3,4,5,6,7,8,9,10
you can also do like this ..
String str = ",1,2,3,4,5,6,7,8,9,10";
String stre = str.replaceFirst("^,", "");
Log.e("abd",stre);
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
if(Objects.nonNull(str) && str.startsWith(",")){
str = str.substring(1, str.length());
}
it will remove , at first position

Java get the same String after split

In Java if you want to split a String by a char or a String you can do that by the split method as follow:
String[] stringWords = myString.split(" ");
But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?
Here is a clear example:
String myString = "This is how the string should be";
String iWant = "This*is*how*the*string*should*be";
Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.
Here is an example:
String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");
myAlgorithmFucntion(stringWords);
Here is an example of how tha final string changes:
String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
If you don't want to use replace or similar, you can use the Apache Commons StringUtils:
String iWant = StringUtils.join(stringWords, "*");
Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.
yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.
String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");
iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
Try something like this as you don't want to use replace() function
char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Try looping the String array:
String[] stringWords = myString.split(" ");
String myString = "";
for (String s : stringWords){
myString = myString + "s" + "*";
}
Just add the logic to deleting the last * of the String.
Using StringBuilder option:
String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
myStringBuilder.append(s).append("*");
}

Separate one String with ',' character into two new String

A MySQL table called item_list has a field named description, the problem is the previous programmer combined the name and description of the item in one field called description. The data is now at 20k+. Now I am going to have a problem during migration.So how do I separate one
String description="BEARING, ROLLER 23230CKE4 SPHERICAL"
into two new strings
String name="BEARING"
String description="ROLLER 23230CKE4 SPHERICAL"
Any help will be appreciated.
you can try this way
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
String [] arr=description.split(",");
System.out.println(arr[0]);
System.out.println(arr[1]);
output
BEARING
ROLLER 23230CKE4 SPHERICAL
String Split methods returns an array of strings.As in the String description has one comma(,) So the whole string will be splited into 2 strings.
You can use StringTokenizer
something like this
StringTokenizer st = new StringTokenizer(description,",");
String name=st.nextToken();
description=st.nextToken();
Unfortunately string split functions will not work correctly if there is more than 1 , in the combined string.
I recommend you split on the first , only.
int idx = description.indexOf(',');
if (idx != -1) { // if there is a comma
name = description.substring(0, idx);
description = description.substring(idx+1);
} else {
???? // no comma in description
}
combination of all the answers.., that solve the problem.
String name="",new_d ="";
String description="BEARING, ROLLER 23230CKE4 SPHERICAL";
int idx = description.indexOf(',');
if (idx != -1) { // if there is comma
String arr[]=description.split(",\\s*");
name=arr[0].toString();
new_d=arr[1].toString();
}
else {
// if there is no comma
name=description;
new_d="";
}
System.out.println(name);
System.out.println(new_d);

Checking whether the String contains multiple words

I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.
There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);
The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;
First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}
You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character
This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}

Easiest way to get every word except the last word from a string

What is the easiest way to get every word in a string other than the last word in a string?
Up until now I have been using the following code to get the last word:
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
And then getting the rest of the the string by using the remove method to remove the last word from the string.
I don't want to have to use the remove method. Is there a way similar to the above set of code to get the string of words without the last word and last space?
Like this:
String test = "This is a test";
String firstWords = test.substring(0, test.lastIndexOf(" "));
String lastWord = test.substring(test.lastIndexOf(" ") + 1);
You could get the lastIndexOf the white space and use a substring like below:
String listOfWords = "This is a sentence";
int index = listOfWords.lastIndexOf(" ");
System.out.println(listOfWords.substring(0, index));
System.out.println(listOfWords.substring(index+1));
Output:
This is a
sentence
Try using the method String.lastIndexOf in combination with String.substring.
String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
I added one line to your code. Nothing was removed here.
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
String rest = listOfWords.substring(0, listOfWords.indexOf(lastWord)).trim(); // Added
System.out.println(rest);
This will suit your needs:
.split("\\s+[^\\s]+$|\\s+")
For example:
"This is a sentence".split("\\s+[^\\s]+$|\\s+");
Returns:
[This, is, a]
public class StringArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String sentence = "this is a sentence";
int index = sentence.lastIndexOf(" ");
System.out.println(sentence.substring(0, index));
}
}

Categories

Resources