I have a string like :
string = abcdefghabcd
Now lets say I want to replace the first occurrence of a. I tried something like this :
string[string.indexOf('a')] = '0'
But this doesn't seems to be working. Any other way I can do this?
Thanks in advance.
In Java you can use String.replaceFirst() :
String s = "abcdefghabcd";
s = s.replaceFirst("a", "0");
System.out.println(s);
Output will be :
0bcdefghabcd
Warning : the replaceFirst() method takes a regex : so if you want to replace a special character like [ you need to escape by putting a \ before it. \ being a special character itself, you need to double it as follow :
s = s.replaceFirst("\\[", "0");
Here is the documentation on Java Regular Expressions. Also, here is Oracle's Java tutorial on manipulating Characters in Strings.
You should be aware that strings in Java are immutable. They cannot be changed. Any method you use to "change" a string will have to return a new string. If you want to modify a string directly you will need to use a mutable string type like StringBuilder.
There are many methods in the String API docs that will help you get a modified version of your string, including s.replace(), s.replaceAll(),s.replaceFirst(), ... or you could use a combination of substring and "+" to create a new string.
If you really want to treat the string as an array as in your initial example, you could use String.getChars to get an array of characters, manipulate that, and then use the String constructor String(char[]) to convert back to a String object.
In this program you will need use replaceFirst() method of String class in Java.
/*
Java String replace example.
This Java String Replace example describes how replace method of java String
class can be used to replace character or substring by new one.
*/
public class JavaStringReplaceExample{
public static void main(String args[])
{
String str="abcdefghabcd";
System.out.println(str.replaceFirst("a", "0"));
}
}
you can refer to here for details
Related
I get some string from server with known and unknow parts. For example:
<simp>example1</simp><op>example2</op><val>example2</val>
I do not wish to parse XML or any use of parsing. What I wish to do is replace
<op>example2</op>
with empty string ("") which string will look like:
<simp>example1</simp><val>example2</val>
What I know it start with op (in <>) and ends with /op (in <>) but the content (example2) may vary.
Can you give me pointer how accomplish this?
You can use regex. Something like
<op>[A-Za-z0-9]*<\/op>
should match. But you can adapt it so that it fits your requirements better. For example if you know that only certain characters can be shown, you can change it.
Afterwards you can use the String#replaceAll method to remove all matching occurrences with the empty string.
Take a look here to test the regex: https://regex101.com/r/WhPIv4/3
and here to check the replaceAll method that takes the regex and the replacement as a parameter: https://developer.android.com/reference/java/lang/String#replaceall
You can try
str.replace(str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5),"");
To remove all, use replaceAll()
str.replaceAll(str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5),"");
I tried sample,
String str="<simp>example1</simp><op>example2</op><val>example2</val><simp>example1</simp><op>example2</op><val>example2</val><simp>example1</simp><op>example2</op><val>example2</val>";
Log.d("testit", str.replaceAll(str.substring(str.indexOf("<op>"), str.indexOf("</op>") + 5), ""));
And the log output was
D/testit: <simp>example1</simp><val>example2</val><simp>example1</simp><val>example2</val><simp>example1</simp><val>example2</val>
Edit
As #Elsafar said , str.replaceAll("<op>.*?</op>", "") will work.
Use like this:
String str = "<simp>example1</simp><op>example2</op><val>example2</val>";
String garbage = str.substring(str.indexOf("<op>"),str.indexOf("</op>")+5).trim();
String newString = str.replace(garbage,"");
I combined all the answers and eventually used:
st.replaceAll("<op>.*?<\\/op>","");
Thank you all for the help
I have a string that I define as
String string = "<html><color=black><b><center>Line1</center><center>Line2</center></b></font></html>";
that I apply to a JButton to get 2 lines of text on it, and that works perfectly. When I call the JButton.getText() method, it returns the whole string. What I want is to take the string it returns, and get the string "Line1Line2" from it. (So I want to remove all the HTML code and just get the text that appears on the screen.) I have tried using something like
if(string.contains("<html>"))
{
string.replace("<html>", "");
}
and then doing the same thing for all the other "<(stuff)>", but if I then print the string, I still get the whole thing. I think using regular expressions is a better way than to manually remove all the "<(stuff)>", but I don't know how.
Any help would be most appreciated!
string.replace() doesn't modify the string: a String is immutable. It returns a new string where the replacement has been done.
So your code should be
if (string.contains("<html>")) {
string = string.replace("<html>", "");
}
String is immutable, so String#replace does not change the String but rather returns the changed String.
string = string.replace("<html>", "");
and so on should do the thing.
String also has a replaceAll() method.
you could try string.replaceAll("<.*?>", "");
Also keep in mind that Strings in java are immutable and this operation will return a new String with your result
OK, this is the line I am working on:
newstring.charAt(w) += p;
trying to add a character/char (p) to the string 'newstring' at a particular position within the string which is defined by int 'w'. Is this possible?
Strings are immutable in Java, so the answer is no. But there are many ways around it. The easiest is to create a StringBuilder and use the setCharAt() method. Or insert() if you want to insert a new character at a given position.
If you make multiple modifications to your string, you can (and indeed should) reuse your StringBuilder.
Well, you can't modify your string, because Strings are immutable in Java. If you try to change the string, you will get a new string object as a result.
Now, you can use String#substring method for that, using which you can get new string which is generated by some concatenation of substring of original string.: -
str = str.substring(0, w) + "p" + str.substring(w);
But, of course, using StringBuilder as specified in #biziclop's answer is the best approach you can follow.
I'm trying to find out if there are any methods in Java which would me achieve the following.
I want to pass a method a parameter like below
"(hi|hello) my name is (Bob|Robert). Today is a (good|great|wonderful) day."
I want the method to select one of the words inside the parenthesis separated by '|' and return the full string with one of the words randomly selected. Does Java have any methods for this or would I have to code this myself using character by character checks in loops?
You can parse it by regexes.
The regex would be \(\w+(\|\w+)*\); in the replacement you just split the argument on the '|' and return the random word.
Something like
import java.util.regex.*;
public final class Replacer {
//aText: "(hi|hello) my name is (Bob|Robert). Today is a (good|great|wonderful) day."
//returns: "hello my name is Bob. Today is a wonderful day."
public static String getEditedText(String aText){
StringBuffer result = new StringBuffer();
Matcher matcher = fINITIAL_A.matcher(aText);
while ( matcher.find() ) {
matcher.appendReplacement(result, getReplacement(matcher));
}
matcher.appendTail(result);
return result.toString();
}
private static final Pattern fINITIAL_A = Pattern.compile(
"\\\((\\\w+(\\\|\w+)*)\\\)",
Pattern.CASE_INSENSITIVE
);
//aMatcher.group(1): "hi|hello"
//words: ["hi", "hello"]
//returns: "hello"
private static String getReplacement(Matcher aMatcher){
var words = aMatcher.group(1).split('|');
var index = randomNumber(0, words.length);
return words[index];
}
}
(Note that this code is written just to illustrate an idea and probably won't compile)
May be it helps,
Pass three strings("hi|hello"),(Bob|Robert) and (good|great|wonderful) as arguments to the method.
Inside method split the string into array
by, firststringarray[]=thatstring.split("|"); use this for other two.
and Use this to use random string selection.
As per my knowledge java don't have any method to do it directly.
I have to write code for it or regexe
I don't think Java has anything that will do what you want directly. Personally, instead of doing things based on regexps or characters, I would make a method something like:
String madLib(Set<String> greetings, Set<String> names, Set<String> dispositions)
{
// pick randomly from each of the sets and insert into your background string
}
There is no direct support for this. And you should ideally not try a low level solution.
You should search for 'random sentence generator'. The way you are writing
`(Hi|Hello)`
etc. is called a grammar. You have to write a parser for the grammar. Again there are many solutions for writing parsers. There are standard ways to specify grammar. Look for BNF.
The parser and generator problems have been solved many time over, and the interesting part of your problem will be writing the grammar.
Java does not provide any readymade method for this. You can use either Regex as described by Penartur or create your own java method to split Strings and store random words. StringTokenizer class can help you if following second approach.
How can I replace String in xml ..
I've
<schema>src/main/castor/document.xsd</schema>
I need to replace to
<schema>cs/src/main/castor/document.xsd</schema>
If I use simple , xmlInStr is the string form of xml document
xmlInStr.replaceAll(
"src/main/castor/GridDocument.xsd",
"correspondenceCastor/src/main/castor/GridDocument.xsd"
);
I Tried replace instead ,
xmlInStr.replace("src/main/castor/GridDocument.xsd".toCharArray().toString(), "correspondenceCastor/src/main/castor/GridDocument.xsd".toCharArray().toString());
it's not working . any clues
Managed like this
int indx = from.indexOf(from);
xmlInStr = xmlInStr.substring(0,indx) + to + xmlInStr.substring(indx + from.length());
String.replaceAll takes a regular expression as the first argument. Use replace instead.
You use an XML parser to parse and manipulate XML, don't try and use regular expression based string replacement mechanisms it will not work and will only bring pain and suffering.
You can use repalce or replaceAll. Anyway you have to use the value returned by this method. The method does not modify the string itself because String class is immutable.
Both replace() and replaceAll() don't actually replace anything in the string (strings are immutable). They return a new string instead, but you just discard the return value, that's why you don't see it anywhere. By the way, that .toCharArray().toString() looks completely useless to me. A character literal is already a full-fledged String.
But you really should use an XML parser instead. Unless your task is very simple and you're absolutely sure that you don't replace anything that shouldn't be replaced.