How to replace special charactes on specific position [duplicate] - java

This question already has answers here:
Replace a char at Nth position
(3 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
what I want to do is to replace it with 9 if 3 is written in the 3rd character in a data. But I only want to do this for the 3rd character. How can I do it? This code I wrote replaces all 3's in the string with 9.
Regards...
String adana = "123456789133";
if (adana.length() > 2 && adana.charAt(2) == '3'){
final String newText = adana.replace("3", "9");
Log.d("TAG", "onCreate: " + newText);
}

You can use this:
final String newText = adana.replaceAll("3(?<=^\\d{3})", "9");
The regex I used here uses positive look behind to search for occurrence of 3 in the 3rd position of the string. You can use replaceAll() or replaceFirst() since it accepts regex. Both case works.

Try concatenating substrings:
String adana = "123456789133";
if (adana.length() > 2 && adana.charAt(2) == '3') {
final String newText = adana.substring(0,2) + "9" + adana.substring(3);
Log.d("TAG", "onCreate: " + newText);
}

Your code checks relatively correctly, however you are failing to actually do the replacement. When using the replace() method of a string what java will do is replace all occurrences passed as the first parameter with the value passed in the second parameter. So naturally what you are talking about will happen. One way to solve this in this specific case is to do:
String adana = "123456789133";
StringBuilder newText = new StringBuilder();
for (int i = 0; i < adana.length(); i++) {
if (i == 2 && adana.charAt(2) == '3') {
newText.append('9');
} else {
newText.append(adana.charAt(i));
}
}
This strategy will work for any string of any length.
Or if you don't want to use string builders (which is not recommended in this case), you can do:
String newText = "";
for (int i = 0; i < adana.length(); i++) {
if (i == 2 && adana.charAt(2) == '3') {
newText += "9";
} else {
newText += adana.charAt(i);
}
}

Related

How to concatenate Special symbol as colon after every 2 character in Android

I want to concatenate or append special character as colon : after an every 2 character in String.
For Example:
Original String are as follow:
String abc =AABBCCDDEEFF;
After concatenate or append colon are as follow:
String abc =AA:BB:CC:DD:EE:FF;
So my question is how we can achieve this in android.
Thanks in advance.
In Kotlin use chunked(2) to split the String every 2 chars and rejoin with joinToString(":"):
val str = "AABBCCDDEEFF"
val newstr = str.chunked(2).joinToString(":")
println(newstr)
will print
AA:BB:CC:DD:EE:FF
You can try below code, if you want to do without Math class functions.
StringBuilder stringBuilder = new StringBuilder();
for (int a =0; a < abc.length(); a++) {
stringBuilder.append(abc.charAt(a));
if (a % 2 == 1 && a < abc.length() -1)
stringBuilder.append(":");
}
Here
a % 2 == 1 ** ==> this conditional statement is used to append **":"
a < abc.length() -1 ==> this conditional statement is used not to add ":"
in last entry. Hope this makes sense. If you found any problem please let me know.
Use a StringBuilder:
StringBuilder sb = new StringBuilder(abc.length() * 3 / 2);
String delim = "";
for (int i = 0; i < abc.length(); i += 2) {
sb.append(delim);
sb.append(abc, i, Math.min(i + 2, abc.length()));
delim = ":";
}
String newAbc = sb.toString();
Here is the Kotlin way. without StringBuilder
val newString: String = abc.toCharArray().mapIndexed { index, c ->
if (index % 2 == 1 && index < abc.length - 1) {
"$c:"
} else {
c
}
}.joinToString("")
You can combine String.split and String.join (TextUtils.join(":", someList) for android) to first split the string at each second char and join it using the delimiter you want. Example:
String abc = "AABBCCDDEEFF";
String def = String.join(":", abc.split("(?<=\\G.{2})"));
System.out.println(def);
//AA:BB:CC:DD:EE:FF

How can i iterate a String and grab several data from there? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have this method:
public void separator(){
int count=0, i=0;
while (count == 0) {
if (track1result.charAt(i) != '^') {
char c = track1result.charAt(i);
number += c;
} else {
count++;
}
i++;
}
}
It's supposed to iterate a String until he reaches the ^ symbol, and that's great, and working so far, the problem is that i'm not sure how can i like keep going from there so i can get the string that's after the symbol and store it in another variable.
If you can give me ideas i would really appreciate it!
you can just split the String into array
String s1 = "hello^world";
String[] arr = s1.split("\\^");
String firstpart = arr[0];
String secondpart = arr[1];
System.out.println(firstpart+" "+secondpart);
Inside the else part add this:
if (i < track1result.length() - 1)
rest = track1result.substring(i + 1);
where rest is previously declared:
String rest = "";

Remove Adjacent duplicate from a string keeping only one instance: java [duplicate]

This question already has answers here:
Java String Manipulation : Comparing adjacent Characters in Java
(12 answers)
Closed 7 years ago.
It is difficult to say in words so i ll use examples. Consider following inputs:-
Input String = AABBSTUUUX
Output String = ABSTUX
How to achieve this in java.
This should do it
String word = "AABBSTUUUX";
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
word.deleteCharAt(i + 1);
}
}
System.out.println(word);
Steps:
Scan the String from first to last
Add each character in in a char type variable temp
Compare each character to the temp except for the first (marked by index 0) character and delete the duplicate
An implementation similar to #Razib's solution above:
public String removeDupes(String in) {
if (in == null || in.length() <= 1) {
return in;
}
char lastLetter = in.charAt(0);
String out = String.valueOf(lastLetter);
for (int i = 1; i < in.length(); i++) {
char nextLetter = in.charAt(i);
if (nextLetter != lastLetter) {
out += nextLetter;
}
lastLetter = nextLetter;
}
return out;
}
Obviously, this is case-sensitive and will remove duplicate non-word characters as well.

Java's String.replaceAll not working [duplicate]

This question already has an answer here:
Why String.replaceAll() don't work on this String?
(1 answer)
Closed 8 years ago.
I'm building a string that represents a polynomial. I'm trying to replace all ^1 and x^0 with "" to simplify the output using the replaceAll method. However when I run the code, it does not detect any of the target strings.
public String toString() {
String output = "";
boolean isFirst = true;
for(Node current = head; current != null; current = current.next) {
if(isFirst) {
output += current.coefficient + "x^" + current.exponent;
isFirst = false;
}
else if(current.coefficient < 0)
output += " - " + current.coefficient*-1 + "x^" + current.exponent;
else
output += " + " + current.coefficient + "x^" + current.exponent;
}
output.replaceAll("x^0", "");
output.replaceAll("^1", "");
return output;
}
Strings are immutable. You cannot alter a String. As such, the replace and replaceAll methods return a new String. Here try this:
output = output.replaceAll("x^0", "");
output = output.replaceAll("^1", "");
Because Strings are immutable, any modifying operation returns a new string. Thus, you must save and work on with the function result:
output = output.replace(...)
Also, please take a look at the definite spec for allowed patterns: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
The one point i want to call out is that a ^ at the start of a string anchors the pattern to the beginning of the string. You do not want that, so escape it: \^.
Anyway, you really want to remove the calls to replaceAll: "x^1" matches the beginning of "x^10"! Just don't include those substrings when you build your string.
double f = current.coefficient;
if(isFirst)
isFirst = false;
else if(f < 0) {
f = -f;
output += " - ";
} else
output += " + ";
output += f;
if(current.exponent == 1)
output += "x";
else if(current.exponent != 0)
Strings are immutable. If you look at the documentation, you'll see that every method that modify the content of a String returns a new one.
So you need to assign back the result of replaceAll to output.
output = output.replaceAll("x^0", "");

String Manipulation insert a character every 4th character [duplicate]

This question already has answers here:
Putting char into a java string for each N characters
(12 answers)
Closed 6 years ago.
In Android if I have an edit text and the user entered 123456789012, how could I get the program to insert a dash every 4th character. ie: 1234-5678-9012?
I guess you need to say something along the lines of:-
a=Characters 1~4, b=Characters 5~8, c=Characters 9-12, Result = a + "-" + b + "-" + c. But I am unsure of how that would look in Android.
Many thanks for any help.
String s = "123456789012";
String s1 = s.substring(0, 4);
String s2 = s.substring(4, 8);
String s3 = s.substring(8, 12);
String dashedString = s1 + "-" + s2 + "-" + s3;
//String.format is extremely slow. Just concatenate them, as above.
substring() Reference
Or another alternative way using a StringBuilder rather than to split the string in multiple parts and then join them :
String original = "123456789012";
int interval = 4;
char separator = '-';
StringBuilder sb = new StringBuilder(original);
for(int i = 0; i < original.length() / interval; i++) {
sb.insert(((i + 1) * interval) + i, separator);
}
String withDashes = sb.toString();
Alternative way:
String original = "123456789012";
int dashInterval = 4;
String withDashes = original.substring(0, dashInterval);
for (int i = dashInterval; i < original.length(); i += dashInterval) {
withDashes += "-" + original.substring(i, i + dashInterval);
}
return withDashes;
If you needed to pass strings with lengths that were not multiples of the dashInterval you'd have to write an extra bit to handle that to prevent index out of bounds nonsense.

Categories

Resources