String replace according to position? - java

I have this String 11101011.I want to replace last three char '011' with 101.is there any function of String in java to do so?

Use string.replaceAll function.
string.replaceAll(".{3}$", "101");
.{3} matches exactly three characters and $ asserts that the match must be followed by an end of the line.
Example:
String name = "11101011";
String result = name.replaceAll(".{3}$", "101");
System.out.println(result);
Output:
11101101

Using String replace and regular expressions for this task seems like breaking butterflies on a wheel - just cut the last three characters off and append the new suffix (ultimately verbose solution):
final String oldString = "11101011";
final String oldSuffix = oldString.substring(5);
final String reducedOldString = oldString.substring(0, oldString.length() - oldSuffix.length());
final String newSuffix = "101";
final String newString = reducedOldString.concat(newSuffix);
System.out.println("newString = " + newString);

Use replace method of String class
String s="11101011";
System.out.println(s.replace("011","101"));
O/P:
11101101

Related

How to put new string between commas in original string

I have this original string and I want to insert new string between two dots of original string. I did it this way, but having errors.
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace);
it gives me: "asdASfasdlpe.NewString"
Result should be: "asdASfasdlpe.NewString.asdasfdfepw"
I would do it like so.
from the question it looks like you want to replace the first occurrence so use replaceFirst
(?<=\\.) - look behind assertion - so start with following character
(?=\\.) - look ahead assertion - so end prior to that
.*? - reluctant quantifier to limit to just characters between two periods. Use * in case you have two adjacent periods since the string could be empty.
String s = "first.oldstring.third.fourth.fifth";
String n = "second";
s = s.replaceFirst("(?<=\\.).*?(?=\\.)",n);
System.out.println(s);
prints
first.second.third.fourth.fifth
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String a[]=originalString.split("[.]");
String newString="";
if(a.length==3) {
newString=originalString.replace(a[1], stringForReplace);
}
System.out.println(newString);
Or with ternary operator:
newString=(a.length== 3 ? originalString.replace(a[1], stringForReplace):null);
System.out.println(newString);
One shorter solution is to use regex with a lookahead and lookbehind
String replaced = originalString.replaceAll("(?<=\\.).+(?=\\.)", stringForReplace);
The problem with your code is due to using this particular piece of code:
originalString.substring(originalString.indexOf(".") + 1)
The reason is that indexof() function will only give the index on which "." was found on, and substring will only know where to start taking the substring from, but it wouldn't know where to end it.
Try this:
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newString = originalString.replace(originalString.split("[.]", 3)[1], stringForReplace);
System.out.println(newString);
The split function in this piece of code will break the whole string by "."
and you will have the string you want to replace available to you.
originalString.split("[.]", 3)[1]
You could try the following:
public static void main(String[] args) {
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newStr = originalString.replaceAll("(?<=\\.).*(?=\\.)", stringForReplace);
//using lookahead and lookbehind regex
String newStr2 = originalString.replaceAll("\\..*\\.", "."+stringForReplace+".");
System.out.println(newStr);
System.out.println(newStr2);
}
One option uses lookahead and lookbehinds, you could opt to not use that if it is not supported.
Output:
asdASfasdlpe.NewString.asdasfdfepw
asdASfasdlpe.NewString.asdasfdfepw
Here You go:
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace)+originalString.substring(originalString.indexOf(".",originalString.indexOf(".")+1),originalString.length());
What I have done is adding the resultant string to the new String.indexOf function takes another argument too, which is the position the search will start

Find Text between special characters and replace string

For instance I have a String that contains:
String s = "test string *67* **Hi**";
I want to to get this String :
*67*
With the stars, so I can start replace that part of the string. My code at the moment looks like this:
String s = "test string *67* **Hi**";
s = s.substring(s.indexOf("*") + 1);
s = s.substring(0, s.indexOf("*"));
This outputs: 67 without the stars.
I would like to know how to get a string between some special character, but not with the characters together, like I want to.
The output should be as followed:
//output: test string hello **hi**
To replace only the string between special characters :
String regex = "(\\s\\*)([^*]+)(\\*\\s)";
String s = "test string *67* **Hi**";
System.out.println(s.replaceAll(regex,"$1hello$3"));
// output: test string *hello* **Hi**
DEMO and Regex explanation
EDIT
To remove also the special characters use below regex:
String regex = "(\\s)(\\*[^*]+\\*)(\\s)";
DEMO
You just need to extend boundaries:
s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1)+1);
s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1) + 1);
Your +1 is in the wrong place :) Then you just need to find the next one starting from the second position
I think you can even get your output with List as well
String s = "test string *67* **Hi**";
List<String> sList = Arrays.asList(s.split(" "));
System.out.println(sarray.get(sarray.indexOf("*67*")));
Hope this will help.

Replacing all subsequent characters of a string, after matching a substring

I try to replace a character and all it's following characters within a string with another character.
This is my code so far.
String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
the result should be: "Petabc"
I would highly appreciate any help on this matter!
A way to achive your goal:
search the string for the first appearance of the sequnce you want to replace
use that index and cut the string using String#substring
add your replace sequence to the end of the substring you just created
fin.
Good luck.
EDIT
In code it might look like this (not tested)
public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);
if(index >= 0)
{
return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
return null; //String 'input' doesn't contain String 'replace'
}
You could use a Regular Expression here with String's built-in replaceAll method to very easily do what you want:
original.replaceFirst(toReplace + ".*", replaceWith);
For example:
String original = "testing 123";
String toReplace = "ing";
String replaceWith = "er";
String replaced = original.replaceFirst(toReplace + ".*", replaceWith);
After the above, replaced will be set to "tester".

Get string before first "$"

I want to get the String before the first $. I used the code below but it doesn't give me the required output, which is name
String sInputFld = "name$name22";
String sOutputFld = sInputFld .split("$")[0];
Your problem is because your delimiter is $ that has special meaning in regular expression that used in split(). You have to escape it:
String sOutputFld = sInputFld .split("\\$")[0];
EDIT:
However using split() for extracting only first fragment seems not effective. You can use substring() and index():
int dollarPos = str.indexOf("$"); // here $ is not escaped because regex is not used\
if (dollarPos >= 0) {
fragment = str.substring(0, dollarPos);
}
Use a combination of indexOf and substring for a String. Something of the sort will do:
String s = input.substring(0, input.indexOf('$'));
You can use this method:
String string = "name$name22";
String[] parts = string.split("\\$");
String part1 = parts[0]; // name
String part2 = parts[1]; // name22
Cange your second line to
String sOutputFld = sInputFld .split("\\$")[0];
the $ is a special character in regexp. It means the end of string. so you have to escape it.

Split Java String

Title seems to be simple. But I don't get a good Idea. This is the situation
I have String like this in my Java program
String scz="3282E81WHT-22/24";
I want to split the above string into 3 Strings, such that
first string value should be 3282e81,
Next string should be WHT(ie, the String part of above string and this part is Always of 3 Characters ),
Next String value should be 22/24 (Which will always occur after -)
In short
String first= /* do some expression on scz And value should be "3282e81" */;
String second= /* do some expression on scz And value should be "WHT" */;
String third= /* do some expression on scz And value should be "22/24" */;
Input can also be like
scz="324P25BLK-12";
So 324P25 will be first String, BLK will be second (of 3 Characters). 12 will be third ( After - symbol )
How to solve this?
You can use a regex like this (\d+[A-Z]\d+)([A-Z]+)-([/\d]+) and using Matcher.group(int) method you can get your string splitted into three groups.
Code snippet
String str = "3282E81WHT-22/24";
//str = "324P25BLK-12";
Pattern pattern = Pattern.compile("(\\d+[A-Z]\\d+)([A-Z]+)-([/\\d]+)");
Matcher match = pattern.matcher(str);
System.out.println(match.matches());
System.out.println(match.group(1));
System.out.println(match.group(2));
System.out.println(match.group(3));
Output
true
3282E81
WHT
22/24
Use this to split the entire string in to two
String[] parts = issueField.split("-");
String first = parts[0];
String second= parts[1];
Use this to split the first string into two
if (first!=null && first.length()>=3){
String lastThree=first.substring(first.length()-3);
}
if your String's Second part (WHT) etc will always be of 3 Characters then following code will surely help you
String scz = "3282E81WHT-22/24";
String Third[] = scz.split("-");
String rev = new StringBuilder(Third[0]).reverse().toString();
String Second=rev.substring(0,3);
String First=rev.substring(3,rev.length());
// here Reverse your String Back to Original
First=new StringBuilder(First).reverse().toString();
Second=new StringBuilder(Second).reverse().toString();
System.out.println(First + " " + Second + " " + Third[1]);
You can use subString() method to get this goals.
subString has numbers of overloads.
for first string
String first=scz.subString(0,6);
String second=scz.subString(7,9);
You can use following regex to take out the above type string:
\d+[A-Z]\d{2}|[A-Z]{3}|(?<=-)[\d/]+
In Java, you can use above regex in following way:
Pattern pattern = Pattern.compile("\\d+[A-Z]\\d{2}|[A-Z]{3}|(?<=-)[\\d/]+");
Matcher matcher = pattern.matcher("3282E81WHT-22/24");
while (matcher.find()) {
System.out.println(matcher.group());
}
Output:
3282E81
WHT
22/24
You could us a char array instead of a string so you can access specific characters withing the array.
Example
char scz[] = "3282E81WHT-22/24";
and access the separate characters just by specifying the place in which the array you want to use.
You can try this
String scz="3282E81WHT-22/24";
String[] arr=scz.split("-");
System.out.println("first: "+arr[0].substring(0,7));
System.out.println("second: "+arr[0].substring(7,10));
System.out.println("third: "+arr[1])
Check out my solution -
class Main {
public static void main(String[] args) {
String first = "";
String second = "";
String third = "";
String scz="3282E81WHT-22/24";
String[] portions = scz.split("-");
if (portions.length > 1) {
third = portions[1];
}
String[] anotherPortions = portions[0].split("[a-zA-Z]+$");
if (anotherPortions.length > 0) {
first = anotherPortions[0];
}
second = portions[0].substring(first.length());
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Live Demo.
String scz="3282E81WHT-22/24";
String[] array = scz.split("-");
String str1 = (String) array[0].subSequence(0, 7);
String str2 = array[0].substring(7);
Then the split will be in this order :)
str1
str2
array[1]
if the length of string is fixed for scz, first,second and third the you can use
String first=scz.subString(0,6);
String second=scz.subString(7,9);
String third=scz.subString(10,scz.length());

Categories