I have a phrase on a string and I want to split it on other 5 or more string without spaces.
For example:
String test = "hi/ please hepl meok?";
and I want :
String temp1 = "hi/";
String temp2 = "please";
String temp3 = "help";
String temp4 = "meok?";
I dont want to add that in an array, because I want to split the temp4 to 3 more strings.
eg
->> temp4 after splitting:
temp4 = "me"
temp5 = "ok"
temp6 = "?"
This Question is asked because I want to write a method to decode a String phrase from a LinkedHashMap set with some decodes. Thanks. If my way is wrong please guide me! :)
I dont want to add that in an array, because I want to split the temp4 to 3 more strings. eg
Split the string with String#split, then assign the parts of the resulting array to your individual variables:
String[] parts = theOriginalString.split(" ");
String temp1 = parts[0];
String temp2 = parts[1];
String temp3 = parts[2];
String temp4 = parts[3];
String temp5 = parts[4];
I find the idea of making these separate named variables a bit suspect, but I can see use cases — for instance, if you're about to embark on a bunch of logic where useful names make the code clearer.
Given your string, split() will do the trick
String tokens[] = test.split(" ");
tokens[0] will then be "hi/", tokens[1] will be "please" and so on.
EDIT you're going to be storing your strings in an array first in any case when split is used, use StringTokenizer if you want to loop through them individually.
StringTokenizer st = new StringTokenizer(test);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Related
I need to extract the amount in a string below, I need the string of "1.50",
eg. CARD,S1234,1.50
I try to use indexOf, but then there might be few commas. If I use . for reference, the amount might be 100.50. Either way is not working.
Any idea?
String.split (",") - get last element of the returned array:
String str = "CARD,S1234,1.50";
String arr[] = str.split (",");
System.out.println(arr[arr.length -1]);
Use the .split() method:
String[] arrayString = "CARD,S1234,1.50".split(",");
String lastString = arrayString[arrayString.length - 1];
String s = "CARD,S1234,1.50";
String last = s.substring(s.lastIndexOf(",")+1, s.length);
I am still new at java. I have this basic split string function as below. I need to capture the substrings post split. My question is how to move individually split parts into separate variables instead of printing them? Do I need another array to move them separately? Is there another simpler way to achieve this? In part I, for simplicity, I am assuming the delimiters to be spaces. Appreciate your help!
public class SplitString {
public static void main(String[] args) {
String phrase = "First Second Third";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
String first;
String middle;
String last;
for (int i = 0; i < tokens.length; i++)
{
System.out.println(tokens[i]);
//I need to move first part to first and second part to second and so on
}
}
}
array[index] accesses the indexth element of array, so
first = tokens[0]; // Array indices start at zero, not 1.
second = tokens[1];
third = tokens[2];
You should really check the length first, and if the string you're splitting is user input, tell the user what went wrong.
if (tokens.length != 3) {
System.err.println(
"I expected a phrase with 3 words separated by spaces,"
+ " not `" + phrase + "`");
return;
}
If the number of Strings that you will end up with after the split has taken place is known, then you can simply assign the variables like so.
String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];
If the number of tokens is not known, then there is no way (within my knowledge) to assign each one to a individual variable.
If you're assuming that your String is three words, then it's quite simple.
String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];
if(tokens.length>3)
{
String first=tokens[0];
String middle=tokens[1];
String last=tokens[2];
}
Thanks everyone...all of you have answered me in some way or the other. Initially I was assuming only 3 entries in the input but turns out it could vary :) for now i'll stick with the simple straight assignments to 3 variables until I figure out another way! Thanks.
Hello I have a string and when I try to use replace method in for loop it doesn't work
String phrase="hello friend";
String[] wordds=phrase.split(" ");
String newPhrase="sup friendhello weirdo";
for (int g=0;g<2;g++)
{
finalPhrase+=newPhrase.replace(wordds[g],"");
}
System.out.println(finalPhrase);
It prints out sup hello weirdo and I expect it to print sup weirdo.
What am I doing wrong?
Let's debug it together.
wordds = ["hello", "friend"].
newPhrase = "sup friendhello weirdo".
Then you're running on some g from 0 to 1 (Should be from 0 to wordds.length.
newPhrase.replace(wordds[g],""); will indeed replace as you want, but when you debug your program, you'll notice that you are using += instead of:
newPhrase=newPhrase.replace(wordds[g],"");
Tip for life: use the debugger, it's there to help you.
Try this:
String phrase = "hello friend";
String[] wordds = phrase.split(" ");
String newPhrase = "sup friendhello weirdo";
for (int g = 0; g < 2 ; g++) {
newPhrase = newPhrase.replace(wordds[g], "");
}
System.out.println(newPhrase);
===================================================
updated
few things that you need to correct
you need to remove concat oprator (+), when you try to replace particular word in a sentence. Just assign it after replacing
for each time you enter the loop you are taking the initial declared string, instead you need to use the string which is getting updated each time
what are you doing, is keep append the replaced Phrase to another one
newPhrase = newPhrase.replace(wordds[g],"");
Apart from the suggestions of an immediate fix, you can also consider a regex-based solution, with no loops:
String phrase="hello friend";
String regex=phrase.replace(' ', '|');
String newPhrase="sup friendhello weirdo";
String finalPhrase=newPhrase.replaceAll(regex,"");
System.out.println(finalPhrase);
or, more succinctly:
System.out.println("sup friendhello weirdo"
.replaceAll("hello friend".replace(' ','|'),
""));
This should do the trick:
String phrase="hello friend";
String[] wordds=phrase.split(" ");
String newPhrase="sup friendhello weirdo";
String finalPhrase=newPhrase;
for (int g=0;g<wordds.length;g++)
{
finalPhrase=finalPhrase.replace(wordds[g],"");
}
System.out.println(finalPhrase);
First you assign finalPhrase to your newPhrase. Then you iterate over all split words (i've changed your magic constant 2 into number of split words wordds.length. Every word will be replaced in the finalPhrase string. The resulting string looks like sup weirdo (it has two spaces between words).
You can clean extra spaces using the answer from here:
System.out.println(finalPhrase.trim().replaceAll(" +", " "));
I have a String in java :
String str = "150,def,ghi,jkl";
I want to get sub string till first comma, do some manipulations on it and then replace it by modified string.
My code :
StringBuilder sBuilder = new StringBuilder(str);
String[] temp = str.split(",");
String newVal = Integer.parseInt(temp[0])*10+"";
int i=0;
for(i=0; i<str.length(); i++){
if(str.charAt(i)==',') break;
}
sBuilder.replace(0, i, newVal);
What is the best way to do this because I am working on big data this code will be called millions of times, I am wondering if there is possibility of avoiding for loop.
You also can use the method replace() of String Object itself.
String str = "150,def,ghi,jkl";
String[] temp = str.split(",");
String newVal = Integer.parseInt(temp[0])*10+"";
String newstr = newVal + str.substring(str.indexOf(","),str.length());
String str = "150,def,ghi,jkl";
String newVal = Integer.parseInt(str.substring(0,str.indexOf(",")))*10+"";
This should at least avoid excessive String concatenation and regular expressions.
String prefix = sBuilder.substring(0, sBuilder.indexOf(","));
String newVal = ...;
sBuilder.replace(0, newVal.length(), newVal);
Don't now if this is useful to you but we often use :
org.springframework.util.StringUtils
In the StringUtils class you have alot of useful methods for comma seperated files.
How slice string in java? I'm getting row's from csv, and xls, and there for example data in cell is like
14.015_AUDI
How can i say java that it must look only on part before _ ? So after manipulating i must have 14.015. In rails i'll do this with gsub, but how do this in java?
You can use String#split:
String s = "14.015_AUDI";
String[] parts = s.split("_"); //returns an array with the 2 parts
String firstPart = parts[0]; //14.015
You should add error checking (that the size of the array is as expected for example)
Instead of split that creates a new list and has two times copy, I would use substring which works on the original string and does not create new strings
String s = "14.015_AUDI";
String firstPart = s.substring(0, s.indexOf("_"));
String str = "14.015_AUDI";
String [] parts = str.split("_");
String numberPart = parts[0];
String audi = parts[1];
Should be shorter:
"14.015_AUDI".split("_")[0];
Guava has Splitter
List<String> pieces = Splitter.on("_").splitToList("14.015_AUDI");
String numberPart = parts.get(0);
String audi = parts.get(1);
you can use substring!
"substring(int begIndex, int endIndex)"
eg:
String name = "14.015_AUDI";
System.out.println(name.substring(0,6));