Java - How to remove special char in string array? - java

I'm having an array of strings (phone numbers) and i need to remove +, which is in front of one of the elements (numbers) since it throws an NumberFormatException when i try to cast it to int.
The elements in array are 0888888888 0888123456 +359886001122 and i have already used .split(" ") in order to separate them. I've also tried .split(" +") in order to remove + from the last one, but this didn't work.

You have to use replaceAll instead of split, for example :
"0888888888 0888123456 +359886001122".replaceAll("\\+", "");
this will show you :
0888888888 0888123456 359886001122
//-------------------^------------
Then if you want to split each number you can use split(" ") like this :
String numbers[] = "0888888888 0888123456 +359886001122".replaceAll("\\+", "").split(" ");
System.out.println(Arrays.toString(numbers));
this will give you :
[0888888888, 0888123456, 359886001122]
EDIT
Or like #shmosel said in comment you ca use replace("+", "")

You can replace it with
var lv_numbers = "0888888888 0888123456 +359886001122".replace('+','');

Split uses a regular expression, so you can define to include and optional '+' in the split matcher.
String [] result = "0888888888 0888123456 +359886001122".split("\\s[\\+]{0,1}");

Related

Selectively replace substring [duplicate]

This question already has answers here:
Java - String replace exact word
(6 answers)
Closed 3 years ago.
String str = "hdfCity1kdCity12fsd".
I want to replace only City1 with Goa without replacing City1 sequence in City1X in above String.
I tried using replace function.
str = str.replace("City1", "Goa")
but the result is
str = "hdfGoakdGoa2fsd"
how to do this selective replace? to get this desired result
str = "hdfGoakdCity12fsd";//solution: str.replaceAll("(?<!\\d)City1(?!\\d)", "Goa");
sorry for making my case not clear
Thanks #TiiJ7
In your case you could use replaceFirst(). This will only replace the first occurence of your matched String:
String str = "City1 is beautiful than City12";
str = str.replaceFirst("City1", "Goa");
System.out.println(str);
Will output:
Goa is beautiful than City12
Other than that you could use a more sophisticated regex to match your exact case, see for example this answer.
You can use replaceFirst() or replaceAll() method, but if you want to replace in the middle, you can find the occurrence you are looking for (one example here: Occurrences of substring in a string)
Use the index returned to make 2 substrings: the first part remain unchanged and, in the second part, the first occurrence must be replaced (replaceFirst())
Last: join the two substrings.
you can use the method replaceFirst(regex, replacement) :
String str = "City1 is beautiful than City12";
System.out.println(str.replaceFirst("City1", "Goa")); // Goa is beautiful than City12
If it's just about the first part, you could also use the substring method.
Example:
String str = "City1 is beautiful than City12";
str = "Goa" + str.substring(5);
If you're sure that City1 will not any characters around except whitespace you can use:
String str = "City1 is beautiful than than City12";
str = str.replace("City1 ", "Goa ");
System.out.println(str);
same as yours but additional space at the end of the replacing and new string

Splitting a string starts with $

I am trying to split a string like "$ 12,9608,03" and just want the numbers and convert to an integer.
For splitting how should I use split() in java as there is a space after the $ sign.
Tried with following:
String[] arr_1=mystring.Split(“[\$, ] “);
String array1=arr_1[0];
Sopln(array1);
You can do what you want, I believe, using this:
String splited = "$ 12,9608,03".replaceAll("[^0-9]", "");
Then you will have splitted only the numbers by commas, but as String. Then you can use, for each String you got, Integer.valueOf() method.
String[] splitted = mystring.split(" ");
String numb = splitted[1];
Just split on the whitespace.
Just like that:
String[] arr_1=mystring.Split("$");
String array1=arr_1[0].trim();
Sopln(array1);
use space in regular experssion to split the string.
String[] split = str.split("( )");
System.out.println(split[1]);
Some fine answers here, to finish off the whole question
and convert to an integer
Here you are:
String myString = "$ 12,9608,03";
String[] splitted = myString.split(" ");
int numb = Integer.parseInt(splitted[1].replaceAll(",", ""));
System.out.println(numb);
To take just the digits, you'd do better with replace:
mystring.replaceAll("[^0-9]", "")
The first parameter is a regex that matches anything but a digit. So this will return you just the number
Stop being insane. Almost everything you will ever do (applies to all readers) has already been done (often better) by the Apache Commons project.
Read the Apache Commons StringUtils API page, pay attention to the RemoveAll method.
Use the StringUtils.RemoveAll method.
Convert the output from the StringUtils.RemoveAll method to an int;
catch any exceptions and handle them appropriately.

Difficulty splitting string at delimiter and keeping it

I have a string that is read in pairs, separated by comma. However, I do not always want to split at the comma because there is not always 1 comma in the input. For example, the string,
(http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b
,http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6,file:///tmp/foo/bar/p,d,f.pdf)
Is read in all one line. For this case, I only want to split at the ,h, and no where else in the string. Essentially, after the split, the strings should be:
http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b
http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6
file:///tmp/foo/bar/p,d,f.pdf
Maintaining the order of the comma in the first string. (I will get rid of parenthesis). I have looked at this stack overflow question, and while helpful, does not correctly split this string. This is in Java. Any help is appreciated.
You can use regex to do the split. Please see below code snippet.
String str = "(http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b,http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6)";
String[] strArr = str.split("(,(?=http))");
You will have Array of all the value which would be possible according to your requirement.
Split on 'http' then re-add it.
Psuedo-code
String input = "http://www.wolframalpha.com/input/?i=103%2F30+%3D+4a-3b,+71%2F60+%3D+a+%2B+b
,http://www.wolframalpha.com/input/?i=x%5E2%2B5x%2B6"
List<String> split = input.split('http');
List<String> finalList = new ArrayList<String>();
for(String fixup in split)
{
finalList.put( "http" + fixup );
}
Final should contain the two URLs.

How to get the desired character from the variable sized strings?

I need to extract the desired string which attached to the word.
For example
pot-1_Sam
pot-22_Daniel
pot_444_Jack
pot_5434_Bill
I need to get the names from the above strings. i.e Sam, Daniel, Jack and Bill.
Thing is if I use substring the position keeps on changing due to the length of the number. How to achieve them using REGEX.
Update:
Some strings has 2 underscore options like
pot_US-1_Sam
pot_RUS_444_Jack
Assuming you have a standard set of above formats, It seems you need not to have any regex, you can try using lastIndexOf and substring methods.
String result = yourString.substring(yourString.lastIndexOf("_")+1, yourString.length());
Your answer is:
String[] s = new String[4];
s[0] = "pot-1_Sam";
s[1] = "pot-22_Daniel";
s[2] = "pot_444_Jack";
s[3] = "pot_5434_Bill";
ArrayList<String> result = new ArrayList<String>();
for (String value : s) {
String[] splitedArray = value.split("_");
result.add(splitedArray[splitedArray.length-1]);
}
for(String resultingValue : result){
System.out.println(resultingValue);
}
You have 2 options:
Keep using the indexOf method to get the index of the last _ (This assumes that there is no _ in the names you are after). Once that you have the last index of the _ character, you can use the substring method to get the bit you are after.
Use a regular expression. The strings you have shown essentially have the pattern where in you have numbers, followed by an underscore which is in turn followed by the word you are after. You can use a regular expression such as \\d+_ (which will match one or more digits followed by an underscore) in combination with the split method. The string you are after will be in the last array position.
Use a string tokenizer based on '_' and get the last element. No need for REGEX.
Or use the split method on the string object like so :
String[] strArray = strValue.split("_");
String lastToken = strArray[strArray.length -1];
String[] s = {
"pot-1_Sam",
"pot-22_Daniel",
"pot_444_Jack",
"pot_5434_Bill"
};
for (String e : s)
System.out.println(e.replaceAll(".*_", ""));

Split string containing newline characters Java

Say I have a following string str:
GTM =0.2
Test =100
[DLM]
ABCDEF =5
(yes, it contains newline characters) That I am trying to split with [DLM] delimiter substring like this:
String[] strArr = str.split("[DLM]");
Why is it that when I do:
System.out.print(strArr[0]);
I get this output: GT
and when I do
System.out.print(strArr[1]);
I get =0.2
Does this make any sense at all?
str.split("[DLM]"); should be str.split("\\[DLM\\]");
Why?
[ and ] are special characters and String#split accepts regex.
A solution that I like more is using Pattern#quote:
str.split(Pattern.quote("[DLM]"));
quote returns a String representation of the given regex.
Yes, you're giving a regex which says "split with either D, or L, or M".
You should escape those boys like this: str.split("\[DLM\]");
It's being split at the first M.
Escape the brackets
("\\[DLM\\]")
When you use brackets inside the " ", it reads it as, each character inside of the brackets is a delimiter. So in your case, M was a delimiter
use
String[] strArr = str.split("\\[DLM]\\");
Instead of
String[] strArr = str.split("[DLM]");
Other wise it will split with either D, or L, or M.

Categories

Resources