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 ('')
Related
I have a question about replacing words. I have some strings, each of which looks like this:
String string = "today is a (happy) day, I would like to (explore) more about Java."
I need to replace the words that have parentheses. I want to replace "(happy)" with "good", and "(explore)" with "learn".
I have some ideas, but I don't know how.
for (int i = 0; i <= string.length(), i++) {
for (int j = 0; j <= string.length(), j++
if ((string.charAt(i)== '(') && (string.charAt(j) == ')')) {
String w1 = line.substring(i+1,j);
string.replace(w1, w2)
}
}
}
My problem is that I can only replace one word with one new word...
I am thinking of using a scanner to prompt me to give a new word and then replace it, how can I do this?
The appendReplacement and appendTail methods of Matcher are designed for this purpose. You can use a regex to scan for your pattern--a pair of parentheses with a word in the middle--then do whatever you need to do to determine the string to replace it with. See the javadoc.
An example, based on the example in the javadoc. I'm assuming you have two methods, replacement(word) that tells what you want to replace the word with (so that replacement("happy") will equal "good" in your example), and hasReplacement(word) that tells whether the word has a replacement or not.
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String word = m.group(1);
String newWord = hasReplacement(word) ? replacement(word) : m.group(0);
m.appendReplacement(sb, newWord); // appends the replacement, plus any not-yet-used text that comes before the match
}
m.appendTail(sb); // appends any text left over after the last match
String result = sb.toString();
Use below code for replacing the string.
String string = "today is a (happy) day, I would like to (explore) more about Java.";
string = string.replaceAll("\\(happy\\)", "good");
string = string.replaceAll("\\(explore\\)", "learn");
System.out.println(string);`
What you can do is run a loop from 0 to length-1 and if loop encounters a ( then assign its index to a temp1 variable. Now go on further as long as you encounter ).Assign its index to temp2 .Now you can replace that substring using string.replace(string.substring(temp1+1,temp2),"Your desired string")).
No need to use the nested loops. Better use one loop and store the index when you find opening parenthesis and also for close parenthesis and replace it with the word. Continue the same loop and store next index. As you are replacing the words in same string it changes the length of string you need to maintain copy of string and perform loop and replace on different,
Do not use nested for loop. Search for occurrences of ( and ). Get the substring between these two characters and then replace it with the user entered value. Do it till there are not more ( and ) combinations left.
import java.util.Scanner;
public class ReplaceWords {
public static String replaceWords(String s){
while(s.contains(""+"(") && s.contains(""+")")){
Scanner keyboard = new Scanner(System.in);
String toBeReplaced = s.substring(s.indexOf("("), s.indexOf(")")+1);
System.out.println("Enter the word with which you want to replace "+toBeReplaced+" : ");
String replaceWith = keyboard.nextLine();
s = s.replace(toBeReplaced, replaceWith);
}
return s;
}
public static void main(String[] args) {
String myString ="today is a (happy) day, I would like to (explore) more about Java.";
myString = replaceWords(myString);
System.out.println(myString);
}
}
This snippet works for me, just load the HashMap up with replacements and iterate through:
import java.util.*;
public class Test
{
public static void main(String[] args) {
String string = "today is a (happy) day, I would like to (explore) more about Java.";
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("\\(happy\\)", "good");
hm.put("\\(explore\\)", "learn");
for (Map.Entry<String, String> entry : hm.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
string = string.replaceAll(key, value);
}
System.out.println(string);
}
}
Remember, replaceAll takes a regex, so you want it to display "\(word\)", which means the slashes themselves must be escaped.
I need to validate a string argument if it can be converted to an int Array.
String pattern = "(\\d+[,])+";
String test = "18,32,5,8,10";
test2.matches(pattern2) //returns false as i requires , in the end
Is there any way to ignore last ' , '
Use a group construct to specify that digits should be followed by (, digits) ...
\\d+(?:,\\d+)+
Regex for both array and single element
(\d|\[(\d|,\s*)*])
This regex will work for you (checks for a "valid array") :
public static void main(String[] args) {
String s = "18,32,5,8,10";
System.out.println(s.matches("(?!.*,$)(?!,.*$)(\\d+(?:,|$))+"));
}
Checks and fails for:
multiple continuous commas
comma at beginning
comma at end
You can try
Pattern = "^\d+(,\d+)*$"
text = "10,5,10" (TRUE)
text = "10,5,10," (FALSE)
text = "10,5,10 " (FALSE)
Since I don't know how to use regex and if I were in your place then this would have been my way to do so
String test = "18,32,5,8,10";
String str[]=test.split(",");
int ar[] = new int[str.length];
for(int i = 0; i<ar.length; i++){
ar[i] = Integer.parseInt(str[i]);
}
The problem in this code if any I can see is this that call to parseInt() method must be wrapped in try-catch as it can throw NumberFormatException if your string contains value other than digit and comma(,).
There's a string
String str = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
How do I split it into strings like this
"ggg;ggg;"
"nnn;nnn;"
"aaa;aaa;"
"xxx;xxx;"
???????
Using Regex
String input = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
Pattern p = Pattern.compile("([a-z]{3});\\1;");
Matcher m = p.matcher(input);
while (m.find())
// m.group(0) is the result
System.out.println(m.group(0));
Will output
ggg;ggg;
nnn;nnn;
aaa;aaa;
xxx;xxx;
I assume that the you only want to check if the last segment is similar and not every segment that has been read.
If that is not the case then you would probably have to use an ArrayList instead of a Stack.
I also assumed that each segment has the format /([a-z])\1\1/.
If that is not the case either then you should change the if statement with:
(stack.peek().substring(0,index).equals(temp))
public static Stack<String> splitString(String text, char split) {
Stack<String> stack = new Stack<String>();
int index = text.indexOf(split);
while (index != -1) {
String temp = text.substring(0, index);
if (!stack.isEmpty()) {
if (stack.peek().charAt(0) == temp.charAt(0)) {
temp = stack.pop() + split + temp;
}
}
stack.push(temp);
text = text.substring(index + 1);
index = text.indexOf(split);
}
return stack;
}
Split and join them.
public static void main(String[] args) throws Exception {
String data = "ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
String del = ";";
int splitSize = 2;
StringBuilder sb = new StringBuilder();
for (Iterable<String> iterable : Iterables.partition(Splitter.on(del).split(data), splitSize)) {
sb.append("\"").append(Joiner.on(del).join(iterable)).append(";\"");
}
sb.delete(sb.length()-3, sb.length());
System.out.println(sb.toString());
}
Ref : Split a String at every 3rd comma in Java
Use split with a regex:
String data="ggg;ggg;nnn;nnn;aaa;aaa;xxx;xxx;";
String [] array=data.split("(?<=\\G\\S\\S\\S;\\S\\S\\S);");
S: A non-whitespace character
G: last match/start of string, think of it of a way to skip delimiting if the
previous string matches current one.
?<=:positive look-behind will match semicolon which has string behind it.
Some other answer, that only works given your specific example input.
You see, in your example, there are two similarities:
All patterns seem to have exactly three characters
All patterns occur exactly twice
In other words: if those two properties are really met for all your input, you could avoid splitting - as you know exactly what to find in each position of your string.
Of course, following the other answers for "real" splitting are more flexible; but (theoretically), you could just go forward and do a bunch of substring calls in order to directly access all elements.
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.
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);
}