How to replace special character In Android? - java

I have to create file with user define name. If User can use the special character then i want to replace that special character with my specific string. i found the method like this.
String replaceString(String string) {
return string.replaceAll("special_char","");
}
but how to use this method.?

relpaceAll method is required regular expression and replace string.
string.replaceAll("regularExpression","replaceString");
You can use this regular expression :
"[;\\/:*?\"<>|&']"
e.g.
String replaceString(String string) {
return string.replaceAll("[;\\/:*?\"<>|&']","replaceString");
}

Try
regular expression
static String replaceString(String string) {
return string.replaceAll("[^A-Za-z0-9 ]","");// removing all special character.
}
call
public static void main(String[] args) {
String str=replaceString("Hello\t\t\t.. how\t\t are\t you."); // call to replace special character.
System.out.println(str);
}
output:
Hello how are you

use below function to replace your string
public static String getString(String p_value)
{
String p_value1 = p_value;
if(p_value1 != null && ! p_value1.isEmpty())
{
p_value1 = p_value1.replace("Replace string from", "Replace String to");
return p_value1;
}
else
{
return "";
}
}
example
Replace string from = "\n";
Replace String to = "\r\n";
after using above function \n is replace with \r\n

**this method make two line your string data after specific word **
public static String makeTwoPart(String data, String cutAfterThisWord){
String result = "";
String val1 = data.substring(0, data.indexOf(cutAfterThisWord));
String va12 = data.substring(val1.length(), data.length());
String secondWord = va12.replace(cutAfterThisWord, "");
Log.d("VAL_2", secondWord);
String firstWord = data.replace(secondWord, "");
Log.d("VAL_1", firstWord);
result = firstWord + "\n" + secondWord;
return result;
}

Related

How to remove particular String from String url

I have to remove this.
String removeKey = "problem_keys";
Code
public class Solution {
public static void main(String args[]) {
String removeKey = "problem_keys";
String url = "{\"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;problem_keys:1,35,3,4,5,6,7,15,16,11,12,16;\";}";
StringBuffer sb = new StringBuffer(url);
removeKey(sb, removeKey);
System.out.println(sb.toString());
}
public static void removeKey(StringBuffer url, String removeKey) {
int sIndex = url.indexOf(removeKey);
while (url.charAt(sIndex) != ';') {
url.deleteCharAt(sIndex);
}
url.deleteCharAt(sIndex);
}
}
Expected output.
{"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;}";
Guessing you want also to remove the "values", using java 8:
String toRemove = Arrays.stream(url.split(";")).filter(part -> part.contains(removeKey)).findFirst().orElse("");
String newUrl = url.replace(toRemove, "");
System.out.println(newUrl);
Speaking about the delimeters you can consider adding ";" to the toRemove string in a conditional block.
If you're aim is only to get rid of the string removeKey you can just:
url.replace(removeKey, "");
I would go with this:
String removeKey = "problem_keys;";
url = url.replace(removeKey, "") // Replace the whole "problem_keys;" string with an empty string

How do I remove all whitespaces from a string?

I'm trying to remove all whitespaces from a string. I've googled a lot and found only replaceAll() method is used to remove whitespace. However, in an assignment I'm doing for an online course, it says to use replace() method to remove all whitespaces and to use \n for newline character and \t for tab characters. I tried it, here's my code:
public static String removeWhitespace(String s) {
String gtg = s.replace(' ', '');
gtg = s.replace('\t', '');
gtg = s.replace('\n', '');
return gtg;
}
After compiling, I get the error message:
Error:(12, 37) java: empty character literal
Error:(13, 37) java: empty character literal
Error:(14, 37) java: empty character literal
All 3 refer to the above replace() code in public static String removeWhitespace(String s).
I'd be grateful if someone pointed out what I'm doing wrong.
There are two flavors of replace() - one that takes chars and one that takes Strings. You are using the char type, and that's why you can't specify a "nothing" char.
Use the String verison:
gtg = gtg.replace("\t", "");
Notice also the bug I corrected there: your code replaces chars from the original string over and over, so only the last replace will be effected.
You could just code this instead:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", ""); // use regex
}
Try this code,
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("Original String : "+s);
s = s.replace(" ", "");
System.out.println("Final String Without Spaces : "+s);
}
}
Output :
Original String : Test example hello string replace enjoy hh
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
Another way by using char array :
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("Original String : "+s);
String ss = removeWhitespace(s);
System.out.println("Final String Without Spaces : "+ss);
}
public static String removeWhitespace(String s) {
char[] charArray = s.toCharArray();
String gtg = "";
for(int i =0; i<charArray.length; i++){
if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
gtg = gtg + charArray[i];
}
}
return gtg;
}
}
Output :
Original String : Test example hello string replace enjoy hh
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
If you want to specify an empty character for the replace(char,char) method, you should do it like this:
public static String removeWhitespace(String s) {
// decimal format, or hexadecimal format
return s.replace(' ', (char) 0)
.replace('\f', (char) 0)
.replace('\n', (char) 0)
.replace('\r', '\u0000')
.replace('\t', '\u0000');
}
But an empty character is still a character, therefore it is better to specify an empty string for the replace(CharSequence,CharSequence) method to remove those characters:
public static String removeWhitespace(String s) {
return s.replace(" ", "")
.replace("\f", "")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "");
}
To simplify this code, you can specify a regular expression for the replaceAll(String,String) method to remove all whitespace characters:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", "");
}
See also:
• Replacing special characters from a string
• First unique character in a string using LinkedHashMap

Splitting string on spaces unless in double quotes but double quotes can have a preceding string attached

I need to split a string in Java (first remove whitespaces between quotes and then split at whitespaces.)
"abc test=\"x y z\" magic=\" hello \" hola"
becomes:
firstly:
"abc test=\"xyz\" magic=\"hello\" hola"
and then:
abc
test="xyz"
magic="hello"
hola
Scenario :
I am getting a string something like above from input and I want to break it into parts as above. One way to approach was first remove the spaces between quotes and then split at spaces. Also string before quotes complicates it. Second one was split at spaces but not if inside quote and then remove spaces from individual split. I tried capturing quotes with "\"([^\"]+)\"" but I'm not able to capture just the spaces inside quotes. I tried some more but no luck.
We can do this using a formal pattern matcher. The secret sauce of the answer below is to use the not-much-used Matcher#appendReplacement method. We pause at each match, and then append a custom replacement of anything appearing inside two pairs of quotes. The custom method removeSpaces() strips all whitespace from each quoted term.
public static String removeSpaces(String input) {
return input.replaceAll("\\s+", "");
}
String input = "abc test=\"x y z\" magic=\" hello \" hola";
Pattern p = Pattern.compile("\"(.*?)\"");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer("");
while (m.find()) {
m.appendReplacement(sb, "\"" + removeSpaces(m.group(1)) + "\"");
}
m.appendTail(sb);
String[] parts = sb.toString().split("\\s+");
for (String part : parts) {
System.out.println(part);
}
abc
test="xyz"
magic="hello"
hola
Demo
The big caveat here, as the above comments hinted at, is that we are really using a regex engine as a rudimentary parser. To see where my solution would fail fast, just remove one of the quotes by accident from a quoted term. But, if you are sure you input is well formed as you have showed us, this answer might work for you.
I wanted to mention the java 9's Matcher.replaceAll lambda extension:
// Find quoted strings and remove there whitespace:
s = Pattern.compile("\"[^\"]*\"").matcher(s)
.replaceAll(mr -> mr.group().replaceAll("\\s", ""));
// Turn the remaining whitespace in a comma and brace all.
s = '{' + s.trim().replaceAll("\\s+", ", ") + '}';
Probably the other answer is better but still I have written it so I will post it here ;) It takes a different approach
public static void main(String[] args) {
String test="abc test=\"x y z\" magic=\" hello \" hola";
Pattern pattern = Pattern.compile("([^\\\"]+=\\\"[^\\\"]+\\\" )");
Matcher matcher = pattern.matcher(test);
int lastIndex=0;
while(matcher.find()) {
String[] parts=matcher.group(0).trim().split("=");
boolean newLine=false;
for (String string : parts[0].split("\\s+")) {
if(newLine)
System.out.println();
newLine=true;
System.out.print(string);
}
System.out.println("="+parts[1].replaceAll("\\s",""));
lastIndex=matcher.end();
}
System.out.println(test.substring(lastIndex).trim());
}
Result is
abc
test="xyz"
magic="hello"
hola
It sounds like you want to write a basic parser/Tokenizer. My bet is that after you make something that can deal with pretty printing in this structure, you will soon want to start validating that there arn't any mis-matching "'s.
But in essence, you have a few stages for this particular problem, and Java has a built in tokenizer that can prove useful.
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class Q50151376{
private static class Whitespace{
Whitespace(){ }
#Override
public String toString() {
return "\n";
}
}
private static class QuotedString {
public final String string;
QuotedString(String string) {
this.string = "\"" + string.trim() + "\"";
}
#Override
public String toString() {
return string;
}
}
public static void main(String[] args) {
String test = "abc test=\"x y z\" magic=\" hello \" hola";
StringTokenizer tokenizer = new StringTokenizer(test, "\"");
boolean inQuotes = false;
List<Object> out = new LinkedList<>();
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
if (inQuotes) {
out.add(new QuotedString(token));
} else {
out.addAll(TokenizeWhitespace(token));
}
inQuotes = !inQuotes;
}
System.out.println(joinAsStrings(out));
}
private static String joinAsStrings(List<Object> out) {
return out.stream()
.map(Object::toString)
.collect(Collectors.joining());
}
public static List<Object> TokenizeWhitespace(String in){
List<Object> out = new LinkedList<>();
StringTokenizer tokenizer = new StringTokenizer(in, " ", true);
boolean ignoreWhitespace = false;
while (tokenizer.hasMoreTokens()){
String token = tokenizer.nextToken();
boolean whitespace = token.equals(" ");
if(!whitespace){
out.add(token);
ignoreWhitespace = false;
} else if(!ignoreWhitespace) {
out.add(new Whitespace());
ignoreWhitespace = true;
}
}
return out;
}
}

Android - How to check the existence of a string value in another comma separated string

Android - How to check the existence of a string value in another comma separated string .
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "456";
How to check like,
if (all_vals contains check_val) {
}
Convert the comma-separated string to an array with split, then convert it to a List with Arrays.asList, then use contains.
String all_vals = "617,618,456,1,234,5,5678,225";
List<String> list = Arrays.asList(all_vals.split(","));
if (list.contains(check_val)) {
}
This will prevent the false positives from just checking if the substring exists in the list with contains directly on the string all_vals, e.g. all_vals.contains("4") would return true in the direct String#contains case.
Java 8:
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "5678";
Arrays.stream(all_vals.split(",")).anyMatch(check_val:: equals)
if(Arrays.stream(all_vals.split(",")).anyMatch(check_val:: equals)){
System.out.println("The value is present");
}
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "5678";
int place = 1;
String[] strings = all_vals.split(",");
for (String str : strings) {
if(str.equals(check_val))
{
System.out.println("We have string in all_val on place: " + place);
}
place++;
}
String all_vals = "617,618,456,1,234,5,5678,225";
String check_val= "456";
if (all_vals.startsWith(check_val) ||
all_vals.endsWith(check_val) ||
all_vals.contains("," + check_val + ","))
{
System.out.println("value found in string");
}

How to split a string in java based on a regex?

I have data as follows:
String s = "foo.com^null^[]";
String s1 = "bar.com^null^[{\"seen_first\":1357882827,\"seen_last\":1357882827,\"_id\":\"93.170.52.31\",\"exclude_from_publication\":false,\"locked\":false,\"agent\":\"domain_export\",\"web_published\":true,\"version\":\"IPv4\"},{\"seen_first\":1357882827,\"seen_last\":1357882827,\"_id\":\"93.170.52.21\",\"exclude_from_publication\":false,\"locked\":false,\"agent\":\"domain_export\",\"web_published\":true,\"version\":\"IPv4\"}]";
And note that third field.. it can be either [] or a json array.
And I am trying to parse these fields..
Here is my current attempt.
public static void check(String s) {
String [] tokens = s.split("^");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
System.out.println(tokens[2]);
if (tokens[2].trim().equals("[]")) {
System.out.println("here--> " +true);
}
System.out.println("---------");
}
What am i doing wrong?
^ is a metacharacter in a regex, meaning "the start of the string". You need to escape it:
String [] tokens = s.split("\\^");

Categories

Resources