String replace function not working in android - java

I used the following code to replace occurrence of '\' but its not working.
msg="\uD83D\uDE0A";
msg=msg.replace("\\", "|");
I spent a lot of time in Google. But didn't find any solution.
Also tried
msg="\uD83D\uDE0A";
msg=msg.replace("\", "|");

The msg string defined must also use an escape character like this:
msg="\\uD83D\\uDE0A";
msg=msg.replace("\\", "|");
That code will work and it will result in: |uD83D|uDE0A

If you want to show the unicode integer value of a unicode character, you can do something like this:
String.format("\\u%04X", ch);
(or use "|" instead of "\\" if you prefer).
You could go through each character in the string and convert it to a literal string like "|u####" if that is what you want.

From what I understand, you want to get the unicode representation of a string. For that you can use the answer from here.
private static String escapeNonAscii(String str) {
StringBuilder retStr = new StringBuilder();
for(int i=0; i<str.length(); i++) {
int cp = Character.codePointAt(str, i);
int charCount = Character.charCount(cp);
if (charCount > 1) {
i += charCount - 1; // 2.
if (i >= str.length()) {
throw new IllegalArgumentException("truncated unexpectedly");
}
}
if (cp < 128) {
retStr.appendCodePoint(cp);
} else {
retStr.append(String.format("\\u%x", cp));
}
}
return retStr.toString();
}
This will give you the unicode value as a String which you can then replace as you like.

Related

Append single quote (') to a Special Character String using Java

I want to append the single quote for the String which consists of only the special characters. This is what I want to achieve :-
String sp = ''{+#)''&$;
Result should be :-
'''' {+#)''''&$
That means for every single quote we need to append 1 single quote that too at that particular index.
Below is my code which I have tried :-
public static String appendSingleQuote(String randomStr) {
if (randomStr.contains("'")) {
long count = randomStr.chars().filter(ch -> ch == '\'').count();
for(int i=0; i<count; i++) {
int index = randomStr.indexOf("'");
randomStr = addChar(randomStr, '\'', index);
}
System.out.println(randomStr);
}
return randomStr;
}
private static String addChar(String randomStr, char ch, int index) {
return randomStr.substring(0, index) + ch + randomStr.substring(index);
}
But this is giving result like this :-
'''''' {+#)''&$
Any suggestions on this? The String can contain even and odd number of single quotes.
All you need is just replace :
String str = "''{+#)''&$";
str = str.replace("'", "''");
Outputs
''''{+#)''''&$
You will just need to use String .replaceAll() method:
String sp =" ''{+#)''&$";
sp.replaceAll("\'", "''")
This is a live working Demo.
Note:
Using a for loop for this is an overkill when .replace() or .replaceAll() are enough, there is no need to reinvent the wheel.
YCF_L's solution should solve your problem. But if you still want to use your method you can try this one below:
public String appendSingleQuote(String randomStr) {
StringBuilder sb = new StringBuilder();
for (int index = 0 ; index < randomStr.length() ; index++) {
sb.append(randomStr.charAt(index) == '\'' ? "''" : randomStr.charAt(index));
}
return sb.toString();
}
It simply iterates through your string and changes every single quote (') with ('')

Use replaceAll() to replace all occurrences of characters in string

Let's say I have this example string:
String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";
And I want to get this string as a result of a replacement procedure:
String textreplaced = "**/src/pt/data,**/src/pt/groove";
Basically, what I wanted was to replace all occurrences of characters before the /src with **/. This might be tricky and I've tried to capture groups between the comma and the /src text but it doesn't work as I was expecting.
I was using the replaceAll() method (wihtin Jenkins).
Does anyone have any idea how can I get it?
Use positive lookahead:
String text = "Data/DataFrontEnd/src/pt/data,Data/DataBackEnd/src/pt/groove";
System.out.println(text.replaceAll("([\\w/]+)(?=/src)", "**")); // **/src/pt/data,**/src/pt/groove
Here's an alternative non-regex based answer, in case anyone wants it:
String textreplaced = "";
String[] split = text.split(",");
for (int i = 0; i < split.length; i++) {
textreplaced += "**" + split[i].substring(split[i].indexOf("/src"));
if (i != split.length - 1) {
textreplaced += ",";
}
}

How to preserve the punctuation when converting words to Pig Latin?

I've been working on a Java program to convert English words to Pig Latin. I've done all the basic rules such as appending -ay, -way, etc., and special cases like question -> estionquay, rhyme -> ymerhay, and I also dealt with capitalization (Thomas -> Omasthay). However, I have one problem that I can't seem to solve: I need to preserve before-and-after punctuation. For example, What? -> Atwhay? Oh!->Ohway! "hello" -> "ellohay" and "Hello!" -> "Ellohay!" This is not a duplicate by the way, I've checked tons of pig latin questions and I cannot seem to figure out how to do it.
Here is my code so far (I've removed all the punctuation but can't figure out how to put it back in):
public static String scrub(String s)
{
String punct = ".,?!:;\"(){}[]<>";
String temp = "";
String pigged = "";
int index, index1, index2, index3 = 0;
for(int i = 0; i < s.length(); i++)
{
if(punct.indexOf(s.charAt(i)) == -1) //if s has no punctuation
{
temp+= s.charAt(i);
}
} //temp equals word without punctuation
pigged = pig(temp); //pig is the piglatin-translator method that I have already written,
//didn't want to put it here because it's almost 200 lines
for(int x = 0; x < s.length(); x++)
{
if(s.indexOf(punct)!= -1)//punctuation exists
{
index = x;
}
}
}
I get that in theory you could search the string for punctuation and that it should be near the beginning or end, so you would have to store the index and replace it after it is "piglatenized", but I keep getting confused about the for loop part. if you do index = x inside the for-loop, you're just replacing index every time the loop runs.
Help would be appreciated greatly! Also, please keep in mind I can't use shortcuts, I can use String methods and such but not things like Collections or ArrayLists (not that you'd need them here), I have to reinvent the wheel, basically. By the way, in case it wasn't clear, I already have the translating-to-piglatin thing down. I only need to preserve the punctuation before and after translating.
If you are allowed to use regular expressions, you can use the following code.
String pigSentence(String sentence) {
Matcher m = Pattern.compile("\\p{L}+").matcher(sentence);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(pig(m.group()));
}
m.appendTail();
return sb.toString();
}
In plain English, the above code is:
for each word in the sentence:
replace it with pig(word)
But if regular expressions are forbidden, you can try this:
String pigSentence(String sentence) {
char[] chars = sentence.toCharArray();
int i = 0, len = chars.length;
StringBuilder sb = new StringBuilder();
while (i < len) {
while (i < len && !Character.isLetter(chars[i]))
sb.append(chars[i++]);
int wordStart = i;
while (i < len && Character.isLetter(chars[i]))
i++;
int wordEnd = i;
if (wordStart != wordEnd) {
String word = sentence.substring(wordStart, wordEnd - wordStart);
sb.append(pig(word));
}
}
return sb.toString();
}
What you need to do is: remove punctuation if it exists, convert to pig latin, add punctuation back.
Assuming punctuation is always and the end of the string, You can check for punctuation with the following:
String punctuation = "";
for (int i = str.length() - 1; i > 0; i--) {
if (!Character.isLetter(str.charAt(i))) {
punctuation = str.charAt(i) + punctuation;
} else {
break; // Found all punctuation
}
}
str = str.substring(0, str.length() - punctuation.length()); // Remove punctuation
// Convert str to pig latin
// Append punctuation to str
I'd find it troublesome to handle punctuation separate from the translation. For punctuation at the very beginning or very end, you can save them and tag them back on after translating.
But if you remove the punctuations from the middle of the word, it will be rather difficult to replace them back to their correct location. Their indices change from the original word to the pigged word, and by a variable amount. (For some a random example, consider "Hel'lo" and "Quest'ion". The apostrophe shifts left by either 1 or 2, and you won't know which.)
How does your translation method handle punctuation? Do you really need to remove all punctuation before passing it to the translator? I'd suggest having your pigging method handle at least the punctuation in the middle of the word.

Deleting all regex instances starting with char '[' and ending with char ']' from a String

I need to take a String and deleting all the regexes in it starting with character '[' and ending with character ']'.
Now i don't know how to tackle this problem. I tried to convert the String to character array and then putting empty characters from any starting '[' till his closing ']' and then convert it back to a String using toString() method.
MyCode:
char[] lyricsArray = lyricsParagraphElements.get(1).text().toCharArray();
for (int i = 0;i < lyricsArray.length;i++)
{
if (lyricsArray[i] == '[')
{
lyricsArray[i] = ' ';
for (int j = i + 1;j < lyricsArray.length;j++)
{
if (lyricsArray[j] == ']')
{
lyricsArray[j] = ' ';
i = j + 1;
break;
}
lyricsArray[j] = ' ';
}
}
}
String songLyrics = lyricsArray.toString();
System.out.println(songLyrics);
But in the print line of songLyrics i get weird stuff like
[C#71bc1ae4
[C#6ed3ef1
[C#2437c6dc
[C#1f89ab83
[C#e73f9ac
[C#61064425
[C#7b1d7fff
[C#299a06ac
[C#383534aa
[C#6bc168e5
I guess there is a simple method for it. Any help will be very appreciated.
For clarification:
converting "abcd[dsadsadsa]efg[adf%#1]d" Into "abcdefgd"
Or simply use a regular expression to replace all occurences of \\[.*\\] with nothing:
String songLyrics = text.replaceAll("\\[.*?\\]", "");
Where text is ofcourse:
String text = lyricsParagraphElements.get(1).text();
What does \\[.*\\] mean?
The first parameter of replaceAll is a string describing a regular expression. A regular expression defines a pattern to match in a string.
So let's split it up:
\\[ matches exactly the character [. Since [ has a special meaning within a regular expression, it needs to be escaped (twice!).
. matches any character, combine this with the (lazy) zero-or-more operator *?, and it will match any character until it finally finds:
\\], which matches the character ]. Note the escaping again.
Your code below is referencing to the string object and you are then printing the reference songLyrics.
String songLyrics = lyricsArray.toString();
System.out.println(songLyrics);
Replace above two lines with
String songLyrics = new String(lyricsArray);
System.out.println(songLyrics);
Ideone1
Other way without converting it into char array and again to string.
String lyricsParagraphElements = "asdasd[asd]";
String songLyrics = lyricsParagraphElements.replaceAll("\\[.*\\]", "");
System.out.println(songLyrics);
Ideone2
You're printing a char[] and Java char[] does not override toString(). And, a Java String is immutable, but Java does have StringBuilder which is mutable (and StringBuilder.delete(int, int) can remove arbitrary substrings). You could use it like,
String songLyrics = lyricsParagraphElements.get(1).text();
StringBuilder sb = new StringBuilder(songLyrics);
int p = 0;
while ((p = sb.indexOf("[", p)) >= 0) {
int e = sb.indexOf("]", p + 1);
if (e > p) {
sb.delete(p, e + 1);
}
p++;
}
System.out.println(sb);
You are getting "weird stuff" because you are printing the string representation of the array, not converting the array to a String.
Instead of lyricsArray.toString(), use
new String(lyricsArray);
But if you do this, you will find that you are not actually removing characters from the string, just replacing them with spaces.
Instead, you can shift all of the characters left in the array, and construct the new String only up to the right number of characters:
int src = 0, dst = 0;
while (src < lyricsArray.length) {
while (src < lyricsArray.length && lyricsArray[src] != '[') {
lyricsArray[dst++] = lyricsArray[src++];
}
if (src < lyricsArray.length) {
++src;
while (src - 1 < lyricsArray.length && lyricsArray[src - 1] != ']') {
src++;
}
}
}
String lyricsString = new String(lyricsArray, 0, dst);
This is exactly regex string for your case:
\\[([\\w\\%\\#]+)\\]
It's very hard when your plant string is contain special symbol. I can't find shorter regex, without explain special symbol like an exception.
reference: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#cg
================
I'm read your new case, a string contain symbol "-" or something else in
!"#$%&'()*+,-./:;<=>?#\^_`{|}~
add them (with prefix "\\") after \\# on my regex string.

How to replace the same character with deferent value?

I'm facing a problem in replacing character in a string with its index.
e.g I wanna replace every '?' With its index String:
"a?ghmars?bh?" -> will be "a1ghmars8bh11".
Any help is truly appreciated.
P.s I need to solve this assignment today so I can pass it to my instructor.
Thanks in adv.
So far I get to manage replacing the ? With 0; through this piece of code:
public static void main(String[] args) {
String name = "?tsds?dsds?";
String myarray[] = name.split("");
for (int i = 0; i < myarray.length; i++) {
name = name.replace("?", String.valueOf(i++));
}
System.out.println(name);
output:
0tsds0dsds0
it should be:
0tsds5dsds10
For simple replace operations, String.replaceAll is sufficient. For more complex operations, you have to retrace partly, what this method does.
The documentation of String.replaceAll says that it is equivalent to
Pattern.compile(regex).matcher(str).replaceAll(repl)
whereas the linked documentation of replaceAll contains a reference to the method appendReplacement which is provided by Java’s regex package publicly for exactly the purpose of supporting customized replace operations. It’s documentation also gives a code example of the ordinary replaceAll operation:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
Using this template, we can implement the desired operation as follows:
String name = "?tsds?dsds?";
Matcher m=Pattern.compile("?", Pattern.LITERAL).matcher(name);
StringBuffer sb=new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, String.valueOf(m.start()));
}
m.appendTail(sb);
name=sb.toString();
System.out.println(name);
The differences are that we use a LITERAL pattern to inhibit the special meaning of ? in regular expressions (that’s easier to read than using "\\?" as pattern). Further, we specify a String representation of the found match’s location as the replacement (which is what your question was all about). That’s it.
In previous answer wrong read question, sorry. This code replace every "?" with its index
String string = "a?ghmars?bh?das?";
while ( string.contains( "?" ) )
{
Integer index = string.indexOf( "?" );
string = string.replaceFirst( "\\?", index.toString() );
System.out.println( string );
}
So from "a?ghmars?bh?das?" we got "a1ghmars8bh11das16"
You are (more or less) replacing each target with the cardinal number of the occurrence (1 for 1st, 2 for 2nd, etc) but you want the index.
Use a StringBuilder - you only need a few lines:
StringBuilder sb = new StringBuilder(name);
for (int i = name.length - 1; i <= 0; i--)
if (name.charAt(i) == '?')
sb.replace(i, i + 1, i + "");
Note counting down, not up, allowing for the replacement index to be multiple digits, which if you counted up would change the index of subsequent calls (eg everything would get shuffled to the right by one char when the index of "?" was 10 or more).
I think this may work i have not checked it.
public class Stack{
public static void main(String[] args) {
String name = "?tsds?dsds?";
int newvalue=50;
int countspecialcharacter=0;
for(int i=0;i<name.length();i++)
{
char a=name.charAt(i);
switch(a)
{
case'?':
countspecialcharacter++;
if(countspecialcharacter>1)
{
newvalue=newvalue+50;
System.out.print(newvalue);
}
else
{
System.out.print(i);
}
break;
default:
System.out.print(a);
break;
}
}
}
}
Check below code
String string = "a?ghmars?bh?das?";
for (int i = 0; i < string.length(); i++) {
Character r=string.charAt(i);
if(r.toString().equals("?"))
System.out.print(i);
else
System.out.print(r);
}

Categories

Resources