I need to remove a ';' from a string array. Any solutions?
What I did in my class was retrieving a long piece of string which are connected without spaces
(thisisalongpieceofstringtobeseparated)
I separated them by inserting a ';' between them
(this;is;a;long;piece;of;string;to;be;separated;)
Then I used .split(";") to add them to an array. All is successful but the last index which has a ';'.
this
is
a
long
piece
of
string
to
be
separated;
Need to remove the last ;
As requested, code is below.
while (line != null) {
if(line.contains("../../"))
{
int startIndex = line.indexOf("../../") + 6;
int endIndex = line.indexOf(">", startIndex + 1);
String abc = "http://www.google.com/";
String imageSrc = line.substring(startIndex,endIndex);
//complete full url
String xyz = abc +imageSrc;
xyz = xyz.substring(0,xyz.indexOf('"'));
xyz = xyz +";";
content += xyz;
mStrings = content.split(";");
String str="This; is; my; test;";
String[] strArr=str.split(";");
for(int i=0;i<strArr.length;i++)
{
System.out.println("Str:::"+strArr[i]);
// add strArr[i] to an array or go through Arrays.toString()
}
Nothing special in the code, i mean if you are using spilt() then it's already worked for you, if not then there is something wrong with your code,Post your code to see what exactly wrong with your code or else do this way
I don't think you're telling us the whole story, because a trailing ; will be ignored when you split on ;. See for yourself by running this test code:
public static void main(String[] args) {
System.out.println(Arrays.toString("a;b;c;".split(";")));
}
Output:
[a, b, c]
The "answer" is to do nothing! It should already work!
Wouldn't it be easiest just to remove the final ; from the string before splitting it ? That is, remove the last character (presuming that is always going to be ;) :
var newStr = str.substring(0, str.length-1);
And then split on that string instead.
Mikel's solution is a lot less work, but you could also use a StringTokenizer and specify returnDelims as false.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
Related
I have a strange behavior on a really simple problem.
I have a string with a lot of null strings:
"a;b;c;null;null;null;null;null;null;null;null;null;null"
Which I remove using this method:
public String replaceAllNull(String s) {
s = s.replaceAll(";null;", ";;");
//if first item = null remove it
if(s.startsWith("null;")) {
s = s.substring(4,s.length());
}
//if last item = null remove it
if(s.endsWith(";null")) {
s = s.substring(0,s.length()-4);
}
return s;
}
It was working fine until my string became bigger and I saw this strange output
"a;b;c;;null;;null;;null;;null;;"
It's only removing one occurrence out of two.
I think I can understand that during one replace program skips one ";" then the second null is not recognized by my regex ";null;". But I don't get why is this happening?
After one instance of ";null;" is replaced by ";;", then both of the semicolons are already processed, so that the second ; cannot be considered as the start of another replacement for the next ";null;" occurrence. The pattern cannot be matched again until after another "null" has been passed up, to reach the next semicolon.
What you can use is a pattern that doesn't attempt to match the semicolons, but it must check to see if they are there. You can use a positive lookbehind and a positive lookahead (find "lookahead" and "lookbehind" on the linked page). Here, positive means that it verifies that the pattern of the lookbehind/lookahead exists, but doesn't match it.
The positive lookbehind is of the format (?<=X), where X is the pattern to look behind the main pattern to see if it exists. Also, the positive lookahead is of the format (?=X), where X is the pattern to look ahead of the main pattern to see if it exists.
Here, we look for the beginning of the line ^ or a semicolon before the match, and the end of the line $ or a semicolon after the match. Then we simply replace the actual match, "null", with an empty string.
s = s.replaceAll("(?<=^|;)null(?=$|;)", "");
You can use a Stream by splitting the String
return Stream.of(s.split(";", -1))
.map(w -> "null".equals(w) ? "" : w)
.collect(Collectors.joining(";"));
A very simple solution, use this instead of the above big code
public String replaceAllNull(String s) {
return s.replace("null" , "");
}
Example
public static void main(String []args){
String str = "a;r;c;e;null;d;f;e;null;s;null;null;null;null;null;null;null;null;null;null;null;null;null;null;null;null;s;";
System.out.println(String.format("Before replacing null %s", str));
str = replaceAllNull(str);
System.out.println(String.format("After replacing null %s", str));
}
Output
Before replacing null a;r;c;e;null;d;f;e;null;s;null;null;null;null;null;null;null;null;null;null;null;null;null;null;null;null;s;
After replacing null a;r;c;e;;d;f;e;;s;;;;;;;;;;;;;;;;;s;
Update to avoid such words that contains null in it, an alternate is here
public static String replaceAllNull(String s) {
String[] arr = s.split(";");
for (int i = 0; i < arr.length; i++) {
if (arr[i].equalsIgnoreCase("null"))
arr[i] = "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
if (i < arr.length - 1)
sb.append(";");
}
if (s.endsWith(";"))
sb.append(";");
return sb.toString();
}
Can someone help me here? I dont understand where's the problem...
I need check if a String have more than 1 char like 'a', if so i need replace all 'a' for a empty space, but i still want only one 'a'.
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
the application stops working when it enters the while loop. Any suggestion? Thank you very much!
If you want to replace every a in the string except for the last one then you may try the following regex option:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
Edit:
If you really want to remove every a except for the last one, then use this:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
You can also do it like
String str = new String ("asomethingsomethingaaaa");
int firstIndex = str.indexOf("a");
firstIndex++;
String firstPart = str.substring(0, firstIndex);
String secondPart = str.substring(firstIndex);
System.out.println(firstPart + secondPart.replace("a", ""));
Maybe I'm wrong here but I have a feeling your talking about runs of any single character within a string. If this is the case then you can just use a little method like this:
public String removeCharacterRuns(String inputString) {
return inputString.replaceAll("([a-zA-Z])\\1{2,}", "$1");
}
To use this method:
String text = "aaaasomethingsomethingaaaa";
System.out.println(removeCharacterRuns(text));
The console output is:
asomethingsomethinga
Or perhaps even:
String text = "FFFFFFFourrrrrrrrrrrty TTTTTwwwwwwooo --> is the answer to: "
+ "The Meeeeeaniiiing of liiiiife, The UUUniveeeerse and "
+ "Evvvvverything.";
System.out.println(removeCharacterRuns(text));
The console output is........
Fourty Two --> is the answer to: The Meaning of life, The Universe and Everything.
The Regular Expression used within the provided removeCharacterRuns() method was actually borrowed from the answers provided within this SO Post.
Regular Expression Explanation:
I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.
I need to validate a string argument if it can be converted to an int Array.
String pattern = "(\\d+[,])+";
String test = "18,32,5,8,10";
test2.matches(pattern2) //returns false as i requires , in the end
Is there any way to ignore last ' , '
Use a group construct to specify that digits should be followed by (, digits) ...
\\d+(?:,\\d+)+
Regex for both array and single element
(\d|\[(\d|,\s*)*])
This regex will work for you (checks for a "valid array") :
public static void main(String[] args) {
String s = "18,32,5,8,10";
System.out.println(s.matches("(?!.*,$)(?!,.*$)(\\d+(?:,|$))+"));
}
Checks and fails for:
multiple continuous commas
comma at beginning
comma at end
You can try
Pattern = "^\d+(,\d+)*$"
text = "10,5,10" (TRUE)
text = "10,5,10," (FALSE)
text = "10,5,10 " (FALSE)
Since I don't know how to use regex and if I were in your place then this would have been my way to do so
String test = "18,32,5,8,10";
String str[]=test.split(",");
int ar[] = new int[str.length];
for(int i = 0; i<ar.length; i++){
ar[i] = Integer.parseInt(str[i]);
}
The problem in this code if any I can see is this that call to parseInt() method must be wrapped in try-catch as it can throw NumberFormatException if your string contains value other than digit and comma(,).
I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}