I have an output like
1054273,
1148244,
1174481,
1175759,
1180656,
1181151,
I need to remove the comma at the end.
I tried the code :
str = str.replaceAll(", $", "");
But the output shows like all the commas were removed.
Can anyone help me to solve this??
Thanks,
SK
String text = "1054273, 1148244, 1174481, 1175759, 1180656, 1181151,".trim();
if(text.endsWith(","))
text = text.substring(0, text.lastIndexOf(","))
The original text is trimmed to ensure that you don't have trailing space. Assuming you have a valid-length string.
If you want to remove a character, why are you replacing it?
Say that you want to remove the last character, because, in fact, the comma is at the end (and I guess it will always be):
str = str.substring(0, str.length() - 1);
you can use substring like this
String str = "1054273, 1148244, 1174481, 1175759, 1180656, 1181151,";
String output = str.substring(0, str.length()-1);
System.out.println(output);
output is :
1054273, 1148244, 1174481, 1175759, 1180656, 1181151
or if you want to create a custom output you'd better use split and create an array of string like this :
String[] outputArrays = str.split(",");
Arrays.asList(outputArrays).stream().forEach(System.out::println);
output is (and you free to change it):
1054273
1148244
1174481
1175759
1180656
1181151
In your case you can simply remove the last char.
With substring :
str = str.substring(0, str.length() - 1);
With regex :
str = str.replaceAll(".$", "");
Related
How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));
I want to split Area Code and preceding number from Telephone number without brackets so i did this.
String pattern = "[\\(?=\\)]";
String b = "(079)25894029".trim();
String c[] = b.split(pattern,-1);
for (int a = 0; a < c.length; a++)
System.out.println("c[" + a + "]::->" + c[a] + "\nLength::->"+ c[a].length());
Output:
c[0]::-> Length::->0
c[1]::->079 Length::->3
c[2]::->25894029 Length::->8
Expected Output:
c[0]::->079 Length::->3
c[1]::->25894029 Length::->8
So my question is why split() produces and extra blank at the start, e.g
[, 079, 25894029]. Is this its behavior, or I did something go wrong here?
How can I get my expected outcome?
First you have unnecessary escaping inside your character class. Your regex is same as:
String pattern = "[(?=)]";
Now, you are getting an empty result because ( is the very first character in the string and split at 0th position will indeed cause an empty string.
To avoid that result use this code:
String str = "(079)25894029";
toks = (Character.isDigit(str.charAt(0))? str:str.substring(1)).split( "[(?=)]" );
for (String tok: toks)
System.out.printf("<<%s>>%n", tok);
Output:
<<079>>
<<25894029>>
From the Java8 Oracle docs:
When there is a positive-width match at the beginning of this string
then an empty leading substring is included at the beginning of the
resulting array. A zero-width match at the beginning however never
produces such empty leading substring.
You can check that the first character is an empty string, if yes then trim that empty string character.
Your regex has problems, as does your approach - you can't solve it using your approach with any regex. The magic one-liner you seek is:
String[] c = b.replaceAll("^\\D+|\\D+$", "").split("\\D+");
This removes all leading/trailing non-digits, then splits on non-digits. This will handle many different formats and separators (try a few yourself).
See live demo of this:
String b = "(079)25894029".trim();
String[] c = b.replaceAll("^\\D+|\\D+$", "").split("\\D+");
System.out.println(Arrays.toString(c));
Producing this:
[079, 25894029]
When I split a String :
A.B.C.
by .. I get 4 strings. The fourth being the white space. How can I remove that ?
String tokens[] = text.split("\\.");
for(String token : tokens) {
System.out.println("Token : " + token);
}
If whitespace at the beginning or end is the problem, trim it off:
String tokens[] = text.trim().split("\\.");
Remove all the whitespace with a replaceAll() before your code.
text.replaceAll("\\s+","");
Your String is A.B.C. so that whenever you split that it with . it will be give four substrings only. Even though you use trim() it will give four substrings. So try to remove last . and then split string. You will get proper output.
I am attempting to split a word from its punctuation:
So for example if the word is "Hello?". I want to store "Hello" in one variable and the "?" in another variable.
I tried using .split method but deletes the delimiter (the punctuation) , which means you wouldn't conserve the punctuation character.
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
word = parts[0];
punctuation = parts[1];
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
I am stuck I cant see another method of doing it.
Thanks in advance
You could use a positive lookahead to split so you don't actually use the punctuation to split, but the position right before it:
inWord.split("(?=[,?.!;])");
ideone demo
Further to the other suggestions, you can also use the 'word boundary' matcher '\b'. This may not always match what you are looking for, it detects the boundary between a word and a non-word, as documented: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
In your example, it works, though the first element in the array will be a blank string.
Here is some working code:
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.matches(".*[,?.!;].*")) {
String parts[] = inWord.split("\\b");
word = parts[1];
punctuation = parts[2];
System.out.println(parts.length);
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
You can see it running here: http://ideone.com/3GmgqD
I've also fixed your .contains to use .matches instead.
I think you can use the below regex. But not tried. Give it a try.
input.split("[\\p{P}]")
You could use substring here. Something like this:
String inWord = "hello?";
String word = inWord.substring (0, 5);
String punctuation = inWord.substring (5, inWord.length ());
System.out.println (word);
System.out.println (punctuation);
I want to split and get rid of the comma's in a string like this that are entered into a textfield:
1,2,3,4,5,6
and then display them in a different textfield like this:
123456
here is what i have tried.
String text = jTextField1.getText();
String[] tokens = text.split(",");
jTextField3.setText(tokens.toString());
Can't you simply replace the , ?
text = text.replace(",", "");
If you're going to put it back together again, you don't need to split it at all. Just replace the commas with the empty string:
jTextField3.setText(text.replace(",", ""));
Assuming this is what you really want to do (e.g. you need to use the individual elements somewhere before concatenating them) the following snippet should work:
String s1 = "1,2,3,4,5,6";
String ss[] = s1.split(",", 0);
StringBuilder sb = new StringBuilder();
for (String s : ss) {
// Use each element here...
sb.append(s);
}
String s2 = sb.toString(); // 123456
Note that the String#split(String) method in Java has strange default behavior so using the method that takes an additional int parameter is recommended.
I may be wrong, but I believe that call to split will get rid of the commas. And it should leave tokens an array of just the numbers