Reputation: 11
I have an application which gathers wifi and cellular data usage and sends it as a string of data via SMS - however I need a bit of help modifying the string it sends into the correct format
The way it appears now:
USI;1;3056090866;06/16/58/06/24/13;CN25.48,WN86.957USI;CN34.931,WN16.656
The way I would like it to send in the following manner: (without the second USI in it)
USI;1;3056090866;06/16/58/06/24/13;CN25.48,WN86.957;CN34.931,WN16.656
How can this be accomplished? (I simply want to remove the 2nd occurance of the word USI but I'm not sure how you can programatically remove data using String.format)
CODE SNIPPET:
String info = String.format("USI%sCN%s,WN%s", tag + status + tag + mdn +tag + DToDevice + tag, mobileStr, totalStr + settings.getString("last_month", "0"));
Upvotes: 0
Views: 163
Reputation: 55619
To replace the first USI
that isn't at the start of the string:
String info = String.format(...);
info = info.replaceFirst("(?<=.)USI","");
To replace the second USI
:
String info = String.format(...);
info = info.replaceFirst("(?<=USI.{0,10000})USI","");
(or another solution that may also suit your needs)
Test.
You can similarly use replaceAll
to replace all occurrences.
The above makes use of regular expressions.
(?<=...)
means the characters before must match the given pattern, which is, in the first case, anything / a wild-card (.
). In the second case, we look backwards until we find a USI
. The .{0,10000}
means 0-10000 wild-cards (.*
, which means zero-or-more wild-cards, doesn't work because look-behind needs a max length).
See this for more on Java regex.
Upvotes: 1
Reputation: 164
You could, as a workaround, find the position of the latter USI with String.lastIndexOf and then work with String.substring using that position to split it into two parts without the second USI.
Upvotes: 0
Reputation: 10543
info.replace("USI","")
will remove every instance of "USI"
. Maybe it would suffice to do "USI" + info.replace("USI","")
.
Upvotes: 1