String format with NumberFormat - java

I'm formatting a String that i enter in a JTextField using NumberFormat instance without specifying the location. As a result i have a String that represents a number formatted with white spaces as separator. I have a problem to get rid of the white spaces when i want to use the String for other processes. I have tried string.replaceAll(" ", ""); and string.replaceAll("\\s", ""); but none of it works.
String string = ((JTextField)c).getText();
string = string.replaceAll("\\s", "");
Also when i do int index = string.indexOf(" "); or int index = string.indexOf("\\s"); it returns -1, which means that it doesn't find the character.
When i do
for(Character ch : string.toCharArray()) {
System.out.println("ch : " + ch.isSpaceChar(ch))
}
it returns true for the empty char. How is represented a space char in java ?
I tried also
StringBuilder b = new StringBuilder(((JTextField)c).getText());
String string = b.toString.replaceAll("\\s", "");
System.out.println("string : " + string);
It doesn't replace a thing.

Have you tried string = string.replaceAll(" ", "");? - string is immutable.

String string = "89774lf&933 k880990";
string = string.replaceAll( "[^\\d]", "" );
System.out.println(string);
OUTPUT:
89774933880990
It will eliminate all the char other than digits.

Related

How to split a string from the first space occurrence only Java

I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

Extract a string omitting certain characters in java

This is my string
1 AP(PEAR + ANC)E (CAN anag)
14 EN(T)ICE (NIECE anag)
15 CHIC ("SHEIK" hom)
The string has an answer hidden,
The first string has an answer APPEARANCE and second string has ENTICE
I must extract those particular answer alone from the strings.
I tried to extract those words from it by
String input = "AP(PEAR + ANC)E (CAN anag)";;
String output = input.substring(0, input.indexOf(' '));
System.out.println(output);
Output:
AP(PEAR
As you can see, there is a space after R so the sub-string stops there and so the output. But Is there any way to read till the character 'E'(ie. end of string 'APPEARANCE') ? I want to stop reading if there is a space and if the next character is '(' .
I have another type of string in the same program "EN(T)ICE (NIECE anag)"
String input = "EN(T)ICE (NIECE anag)";
String output = input.substring(0, input.indexOf(' '));
System.out.println(output);
Output:
EN(T)ICE
There is a space after the character 'E' so it successfully gave the full output. Is there any way to get output like this for the first string. ? Any help would be great !!
Use replaceAll instead of indexOf and substring.
String[] inputs = {
"AP(PEAR + ANC)E (CAN anag)",
"EN(T)ICE (NIECE anag)",
"CHIC (\"SHEIK\" hom)"};
for (String s : inputs) {
String output = s.replaceAll(" \\(.*|[()+\\s]", "");
System.out.println(output);
}
result:
APPEARANCE
ENTICE
CHIC
You can try this splitting the string on the index of " (":
String input1 = "EN(T)ICE (NIECE anag)";
String input2 = "AP(PEAR + ANC)E (CAN anag)";
String input3 = "CHIC (\"SHEIK\" hom)";
System.out.println(extract(input1));
System.out.println(extract(input2));
System.out.println(extract(input3));
public static String extract(String s){
return s.split(" \\(.*")[0]
.replace("(", "")
.replace(")", "")
.replace(" + ", "");
}
Will produce :
ENTICE
APPEARANCE
CHIC
Split on the " (";
like so:
String input = "AP(PEAR + ANC)E (CAN anag)";
System.out.println(input.split(" \\(.*")[0]);
Just replace the String input with new values!
Can't you just replace the " + " with nothing, and then split by " " (space)?
Something like this:
private static String convertInputToOutput(final String input) {
String[] splittedArray = input.replaceAll(" \\+ ", "").split(" ");
return splittedArray[0];
}
public static void main(final String[] args) {
System.out.println(convertInputToOutput("AP(PEAR + ANC)E (CAN anag)"));
System.out.println(convertInputToOutput("EN(T)ICE (NIECE anag)"));
System.out.println(convertInputToOutput("CHIC (\"SHEIK\" hom)"));
}
Output:
AP(PEARANC)E
EN(T)ICE
CHIC
If you want output without parenthesis, also use a replaceAll for the parenthesis:
private static String convertInputToOutput(final String input) {
String[] splittedArray = input.replaceAll(" \\+ ", "").split(" ");
return splittedArray[0].replaceAll("(", "").replaceAll(")", "");
}
Output:
APPEARANCE
ENTICE
CHIC

Java PatternSyntaxException when replacing characters in a String object

I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Looking for quick, simple way in Java to change this string
" hello there "
to something that looks like this
"hello there"
where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.
Something like this gets me partly there
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
but not quite.
Try this:
String after = before.trim().replaceAll(" +", " ");
See also
String.trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
regular-expressions.info/Repetition
No trim() regex
It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
There are 3 alternates:
^_+ : any sequence of spaces at the beginning of the string
Match and replace with $1, which captures the empty string
_+$ : any sequence of spaces at the end of the string
Match and replace with $1, which captures the empty string
(_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
Match and replace with $1, which captures a single space
See also
regular-expressions.info/Anchors
You just need a:
replaceAll("\\s{2,}", " ").trim();
where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
To test this out quickly try:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
and it will return:
"hello there"
Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here
This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");
trim() method removes the leading and trailing spaces and using replaceAll("regex", "string to replace") method with regex "\s+" matches more than one space and will replace it with a single space
myText = myText.trim().replaceAll("\\s+"," ");
The following code will compact any whitespace between words and remove any at the string's beginning and end
String input = "\n\n\n a string with many spaces, \n"+
" a \t tab and a newline\n\n";
String output = input.trim().replaceAll("\\s+", " ");
System.out.println(output);
This will output a string with many spaces, a tab and a newline
Note that any non-printable characters including spaces, tabs and newlines will be compacted or removed
For more information see the respective documentation:
String#trim() method
String#replaceAll(String regex, String replacement) method
For information about Java's regular expression implementation see the documentation of the Pattern class
"[ ]{2,}"
This will match more than one space.
String mytext = " hello there ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);
OUTPUT:
hello there
To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext.replaceAll("( )+", " ").
You can first use String.trim(), and then apply the regex replace command on the result.
Try this one.
Sample Code
String str = " hello there ";
System.out.println(str.replaceAll("( +)"," ").trim());
OUTPUT
hello there
First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.
String blogName = "how to do in java . com";
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");
trim()
Removes only the leading & trailing spaces.
From Java Doc,
"Returns a string whose value is this string, with any leading and trailing whitespace removed."
System.out.println(" D ev Dum my ".trim());
"D ev Dum my"
replace(), replaceAll()
Replaces all the empty strings in the word,
System.out.println(" D ev Dum my ".replace(" ",""));
System.out.println(" D ev Dum my ".replaceAll(" ",""));
System.out.println(" D ev Dum my ".replaceAll("\\s+",""));
Output:
"DevDummy"
"DevDummy"
"DevDummy"
Note: "\s+" is the regular expression similar to the empty space character.
Reference : https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html
In Kotlin it would look like this
val input = "\n\n\n a string with many spaces, \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")
A lot of correct answers been provided so far and I see lot of upvotes. However, the mentioned ways will work but not really optimized or not really readable.
I recently came across the solution which every developer will like.
String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );
You are done.
This is readable solution.
You could use lookarounds also.
test.replaceAll("^ +| +$|(?<= ) ", "");
OR
test.replaceAll("^ +| +$| (?= )", "")
<space>(?= ) matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.
Example:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$| (?= )", "")
);
}
See String.replaceAll.
Use the regex "\s" and replace with " ".
Then use String.trim.
String str = " hello world"
reduce spaces first
str = str.trim().replaceAll(" +", " ");
capitalize the first letter and lowercase everything else
str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
you should do it like this
String mytext = " hello there ";
mytext = mytext.replaceAll("( +)", " ");
put + inside round brackets.
String str = " this is string ";
str = str.replaceAll("\\s+", " ").trim();
This worked for me
scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();
where filter is following function and scan is the input string:
public String filter(String scan, String regex, String replace) {
StringBuffer sb = new StringBuffer();
Pattern pt = Pattern.compile(regex);
Matcher m = pt.matcher(scan);
while (m.find()) {
m.appendReplacement(sb, replace);
}
m.appendTail(sb);
return sb.toString();
}
The simplest method for removing white space anywhere in the string.
public String removeWhiteSpaces(String returnString){
returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
return returnString;
}
check this...
public static void main(String[] args) {
String s = "A B C D E F G\tH I\rJ\nK\tL";
System.out.println("Current : "+s);
System.out.println("Single Space : "+singleSpace(s));
System.out.println("Space count : "+spaceCount(s));
System.out.format("Replace all = %s", s.replaceAll("\\s+", ""));
// Example where it uses the most.
String s = "My name is yashwanth . M";
String s2 = "My nameis yashwanth.M";
System.out.println("Normal : "+s.equals(s2));
System.out.println("Replace : "+s.replaceAll("\\s+", "").equals(s2.replaceAll("\\s+", "")));
}
If String contains only single-space then replace() will not-replace,
If spaces are more than one, Then replace() action performs and removes spacess.
public static String singleSpace(String str){
return str.replaceAll(" +| +|\t|\r|\n","");
}
To count the number of spaces in a String.
public static String spaceCount(String str){
int i = 0;
while(str.indexOf(" ") > -1){
//str = str.replaceFirst(" ", ""+(i++));
str = str.replaceFirst(Pattern.quote(" "), ""+(i++));
}
return str;
}
Pattern.quote("?") returns literal pattern String.
My method before I found the second answer using regex as a better solution. Maybe someone needs this code.
private String replaceMultipleSpacesFromString(String s){
if(s.length() == 0 ) return "";
int timesSpace = 0;
String res = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' '){
timesSpace++;
if(timesSpace < 2)
res += c;
}else{
res += c;
timesSpace = 0;
}
}
return res.trim();
}
Stream version, filters spaces and tabs.
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
I know replaceAll method is much easier but I wanted to post this as well.
public static String removeExtraSpace(String input) {
input= input.trim();
ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
for(int i=0; i<x.size()-1;i++) {
if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) {
x.remove(i);
i--;
}
}
String word="";
for(String each: x)
word+=each;
return word;
}
String myText = " Hello World ";
myText = myText.trim().replace(/ +(?= )/g,'');
// Output: "Hello World"
string.replaceAll("\s+", " ");
If you already use Guava (v. 19+) in your project you may want to use this:
CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');
or, if you need to remove exactly SPACE symbol ( or U+0020, see more whitespaces) use:
CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');
public class RemoveExtraSpacesEfficient {
public static void main(String[] args) {
String s = "my name is mr space ";
char[] charArray = s.toCharArray();
char prev = s.charAt(0);
for (int i = 0; i < charArray.length; i++) {
char cur = charArray[i];
if (cur == ' ' && prev == ' ') {
} else {
System.out.print(cur);
}
prev = cur;
}
}
}
The above solution is the algorithm with the complexity of O(n) without using any java function.
Please use below code
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}

how to process string in java

I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();

Categories

Resources