How would I replace a string 10100 with 10010 using the algorithm "replace the last substring 10 with 01."
I tried
s=s.replace(s.substring(a,a+2), "01");
but this returns 01010, replacing both the first and the second substring of "10".
"a" represents s.lastindexOf("10");
Here's a simple and extensible function you can use. First its use/output and then its code.
String original = "10100";
String toFind = "10";
String toReplace = "01";
int ocurrence = 2;
String replaced = replaceNthOcurrence(original, toFind, toReplace, ocurrence);
System.out.println(replaced); // Output: "10010"
original = "This and This and This";
toFind = "This";
toReplace = "That";
ocurrence = 3;
replaced = replaceNthOcurrence(original, toFind, toReplace, ocurrence);
System.out.println(replaced); // Output: "This and This and That"
Function code:
public static String replaceNthOcurrence(String str, String toFind, String toReplace, int ocurrence) {
Pattern p = Pattern.compile(Pattern.quote(toFind));
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer(str);
int i = 0;
while (m.find()) {
if (++i == ocurrence) { sb.replace(m.start(), m.end(), toReplace); break; }
}
return sb.toString();
}
If you want to access the last two indices of a string, then you can use: -
str.substring(str.length() - 2);
This gives you string from index str.length() - 2 to the last character, which is exactly the last two character.
Now, you can replace the last two indices with whatever string you want.
UPDATE: -
Of you want to access the last occurrence of a character or substring, you can use String#lastIndexOf method: -
str.lastIndexOf("10");
Ok, you can try this code: -
String str = "10100";
int fromIndex = str.lastIndexOf("10");
str = str.substring(0, fromIndex) + "01" + str.substring(fromIndex + 2);
System.out.println(str);
10100 with 10010
String result = "10100".substring(0, 2) + "10010".substring(2, 4) + "10100".substring(4, 5);
You can get the last index of a character or substring using string's lastIndexOf method. See the documentation link below for how to use it.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#lastIndexOf(java.lang.String)
Once you know the index of your substring, you can get the substring of all characters before that index, and the substring of all characters after the last character in your search string, and concatenate.
This is a little drawn out, and I didn't actually run it (so I might have a syntax error), but it gives you the point of what I'm trying to convey at least. You could do this all in one line if you want, but it wouldn't illustrate the point as well.
string s = "10100";
string searchString = "10";
string replacementString = "01";
string charsBeforeSearchString = s.substring(0, s.lastIndexOf(searchString) - 1);
string charsAfterSearchString = s.substring(s.lastIndexIf(searchString) + 2);
s = charsBeforeSearchString + replacementString + charsAfterSearchString;
The easiest way:
String input = "10100";
String result = Pattern.compile("(10)(?!.*10.*)").matcher(input).replaceAll("01");
System.out.println(result);
Related
For example I have this string params: Blabla,1,Yooooooo,Stackoverflow,foo,chinese
And I want to get the string testCaseParams until the 3rd comma: Blabla,1,Yooooooo
and then remove it and the comma from the original string so I get thisStackoverflow,foo,chinese
I'm trying this code but testCaseParams only shows the first two values (gets index of the 2nd comma, not 3rd...)
//Get how many parameters this test case has and group the parameters
int amountOfInputs = 3;
int index = params.indexOf(',', params.indexOf(',') + amountOfInputs);
String testCaseParams = params.substring(0,index);
params = params.replace(testCaseParams + ",","");
You can hold the index of the currently-found comma in a variable and iterate until the third comma is found:
int index = 0;
for (int i=0; i<3; i++) index = str.indexOf(',', index);
String left = str.substring(0, index);
String right = str.substring(index+1); // skip comma
Edit: to validate the string, simply check if index == -1. If so, there are not 3 commas in the string.
One option would be a clever use of String#split:
String input = "Blabla,1,Yooooooo,Stackoverflow,foo,chinese";
String[] parts = input.split("(?=,)");
String output = parts[0] + parts[1] + parts[2];
System.out.println(output);
Demo
One can use split with a limit of 4.
String input = "Blabla,1,Yooooooo,Stackoverflow,foo,chinese";
String[] parts = input.split(",", 4);
if (parts.length == 4) {
String first = parts[0] + "," + parts[1] + "," + parts[2];
String second = parts[3]; // "Stackoverflow,foo,chinese"
}
You can split with this regex to get the 2 pats:
String[] parts = input.split("(?<=\\G.*,.*,.*),");
It will result in parts equal to:
{ "Blabla,1,Yooooooo", "Stackoverflow,foo,chinese" }
\\G refers to the previous match or the start of the string.
(?<=) is positive look-behind.
So it means match a comma for splitting, if it is preceded by 2 other commas since the previous match or the start of the string.
This will keep empty strings between commas.
I offer this here just as a "fun" one line solution:
public static int nthIndexOf(String str, String c, int n) {
return str.length() - str.replace(c, "").length() < n ? -1 : n == 1 ? str.indexOf(c) : c.length() + str.indexOf(c) + nthIndexOf(str.substring(str.indexOf(c) + c.length()), c, n - 1);
}
//Usage
System.out.println(nthIndexOf("Blabla,1,Yooooooo,Stackoverflow,foo,chinese", ",", 3)); //17
(It's recursive of course, so will blow up on large strings, it's relatively slow, and certainly isn't a sensible way to do this in production.)
As a more sensbile one liner using a library, you can use Apache commons ordinalIndexOf(), which achieves the same thing in a more sensible way!
So I'm trying to iterate over a string and replace ever occurrence of a given substring with a new value. I can't seem to figure out what the problem with my code is because it doesn't seem to make any changes to the strings i run through it.
i create a new string nS that starts out as just “”, and am iterating through the template viewing each character as a substring s. In in every case that something needs to be replaced with a value i append said value on to the nS, else it just appends the current substring as is.
#Override
public String format(String template) {
String nS = "";
for (int i = 0, n = template.length(); i < n; i++) {
String s = template.substring(i, i + 1);
switch (s) {
case "%%":
nS = nS.concat("%");
break;
case "%t":
nS = nS.concat(String.valueOf(inSeconds()));
break;
}
}
return nS;
}
the actual code has many more cases but i left them out so that its not as overwhelming.
The ending index in the 2-arg substring method is exclusive.
The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
You are getting a substring of exactly one character, not 2. Try i + 2, after the appropriate bounds-checking:
String s = template.substring(i, i + 2);
Assuming performance is not a big issue I would do
public String format(String template) {
return template.replaceAll ("%%", "\uffff")
.replaceAll("%t", ""+inSeconds())
.replaceAll("\uffff", "%");
}
What you're describing attempting to do sounds like you're trying to rewrite String.replace()
Given String s = "My Name Is Bob"
and you would like to replace "Bob" with "Susan" all you need to do is:
String s = "My Name is Bob";
String n = s.replace("Bob", "Susan");
System.out.println(n); //My Name is Susan
System.out.println(s); //My Name is Bob
Another option, is to break the string into a character array and iterate over it.
String s = "My Name is Bob";
char[] bits = s.toCharArray();
for(char c : bits) {
// logic
}
Compare two characters at once:
String s = "My Name is Bob";
char[] bits = s.toCharArray();
for(int i = 0; i < bits.length; i++) {
if(i + 1 <= bits.length) {
String searchFor = "" + bits[i] + bits[i + 1];
// logic
}
}
I have two strings: stringOne and stringTwo.
String stringOne = "JAVA";
String stringTwo = "DJDFKWAUERHFGJAVAORKFLASOWE";
I can easily locate if Java is in the second string (it is), where how would I index where it begins and ends? I want to initialize the beginning and end positions in integer variables: begPos = 14 and endPos = 18. What method would I use to do this?
Somewhat the reverse of this, but I also have a third string:
String stringThree = " ";
It's a bunch of whitespace. I want to put "JAVA" in there according to the positions gained before. I can replace parts of a string with other parts of a string, but again I'm not sure how to replace a specific position. The end result should be:
String stringThree = " JAVA ";
Any ideas?
You're looking for the indexOf() method.
String stringOne = "JAVA";
String stringTwo = "DJDFKWAUERHFGJAVAORKFLASOWE";
int begin=stringTwo.indexOf(stringOne);
int end=begin+stringOne.length();
if(begin==-1){
//not found
}
You could use str.indexOf(substr) which returns the index of a substring into str, and the str.substring(start, end) methods:
public String substring(int beginIndex,
int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Code:
public static void main(String[] args)
{
String stringOne = "JAVA";
String stringTwo = "DJDFKWAUERHFGJAVAORKFLASOWE";
int begPos = stringTwo.indexOf(stringOne);
int endPos = begPos + stringOne.length();
System.out.println(begPos + " " + endPos);
String stringThree = "......................";
stringThree = stringThree.substring(0, begPos) + stringOne + stringThree.substring(endPos);
System.out.println(stringThree);
}
You would like to manipulate the start and end arguments passed to substring(start, end) in order to get the expected output.
If you want to modify the string, use StringBuilder.
String str = " ";
String ins = "JAVA";
StringBuilder builder = new StringBuilder(str);
String result = builder.replace(14, 18, ins).toString();
I have following String and i want to split this string into number of sub strings(by taking ',' as a delimeter) when its length reaches 36. Its not exactly splitting on 36'th position
String message = "This is some(sampletext), and has to be splited properly";
I want to get the output as two substrings follows:
1. 'This is some (sampletext)'
2. 'and has to be splited properly'
Thanks in advance.
A solution based on regex:
String s = "This is some sample text and has to be splited properly";
Pattern splitPattern = Pattern.compile(".{1,15}\\b");
Matcher m = splitPattern.matcher(s);
List<String> stringList = new ArrayList<String>();
while (m.find()) {
stringList.add(m.group(0).trim());
}
Update:
trim() can be droped by changing the pattern to end in space or end of string:
String s = "This is some sample text and has to be splited properly";
Pattern splitPattern = Pattern.compile("(.{1,15})\\b( |$)");
Matcher m = splitPattern.matcher(s);
List<String> stringList = new ArrayList<String>();
while (m.find()) {
stringList.add(m.group(1));
}
group(1) means that I only need the first part of the pattern (.{1,15}) as output.
.{1,15} - a sequence of any characters (".") with any length between 1 and 15 ({1,15})
\b - a word break (a non-character before of after any word)
( |$) - space or end of string
In addition I've added () surrounding .{1,15} so I can use it as a whole group (m.group(1)).
Depending on the desired result, this expression can be tweaked.
Update:
If you want to split message by comma only if it's length would be over 36, try the following expression:
Pattern splitPattern = Pattern.compile("(.{1,36})\\b(,|$)");
The best solution I can think of is to make a function that iterates through the string. In the function you could keep track of whitespace characters, and for each 16th position you could add a substring to a list based on the position of the last encountered whitespace. After it has found a substring, you start anew from the last encountered whitespace. Then you simply return the list of substrings.
Here's a tidy answer:
String message = "This is some sample text and has to be splited properly";
String[] temp = message.split("(?<=^.{1,16}) ");
String part1 = message.substring(0, message.length() - temp[temp.length - 1].length() - 1);
String part2 = message.substring(message.length() - temp[temp.length - 1].length());
This should work on all inputs, except when there are sequences of chars without whitespace longer than 16. It also creates the minimum amount of extra Strings by indexing into the original one.
public static void main(String[] args) throws IOException
{
String message = "This is some sample text and has to be splited properly";
List<String> result = new ArrayList<String>();
int start = 0;
while (start + 16 < message.length())
{
int end = start + 16;
while (!Character.isWhitespace(message.charAt(end--)));
result.add(message.substring(start, end + 1));
start = end + 2;
}
result.add(message.substring(start));
System.out.println(result);
}
If you have a simple text as the one you showed above (words separated by blank spaces) you can always think of StringTokenizer. Here's some simple code working for your case:
public static void main(String[] args) {
String message = "This is some sample text and has to be splited properly";
while (message.length() > 0) {
String token = "";
StringTokenizer st = new StringTokenizer(message);
while (st.hasMoreTokens()) {
String nt = st.nextToken();
String foo = "";
if (token.length()==0) {
foo = nt;
}
else {
foo = token + " " + nt;
}
if (foo.length() < 16)
token = foo;
else {
System.out.print("'" + token + "' ");
message = message.substring(token.length() + 1, message.length());
break;
}
if (!st.hasMoreTokens()) {
System.out.print("'" + token + "' ");
message = message.substring(token.length(), message.length());
}
}
}
}
I have a string that I need to be split into 2. I want to do this by splitting at exactly the third comma.
How do I do this?
Edit
A sample string is :
from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234
The string will keep the same format - I want everything before field in a string.
If you're simply interested in splitting the string at the index of the third comma, I'd probably do something like this:
String s = "from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234";
int i = s.indexOf(',', 1 + s.indexOf(',', 1 + s.indexOf(',')));
String firstPart = s.substring(0, i);
String secondPart = s.substring(i+1);
System.out.println(firstPart);
System.out.println(secondPart);
Output:
from:09/26/2011,type:all,to:09/26/2011
field1:emp_id,option1:=,text:1234
Related question:
How to find nth occurrence of character in a string?
a naive implementation
public static String[] split(String s)
{
int index = 0;
for(int i = 0; i < 3; i++)
index = s.indexOf(",", index+1);
return new String[] {
s.substring(0, index),
s.substring(index+1)
};
}
This does no bounds checking and will throw all sorts of lovely exceptions if not given input as expected. Given "ABCD,EFG,HIJK,LMNOP,QRSTU" returns ["ABCD,EFG,HIJK","LMNOP,QRSTU"]
You can use this regex:
^([^,]*,[^,]*,[^,]*),(.*)$
The result is then in the two captures (1 and 2), not including the third comma.