Java assign matches to variable - java

I am trying to do something like this but I doesnt seem to work
String test = input.matches("[^a-zA-Z\\s]");
I get an error saying incompatible types
Is there any way fixing this or any other methods?
EDIT
This is what I'm trying to achieve
Lets say i have this string
String full = " This i$ an aaasdAr yeEeeAs oofo qwdsgy XY9 ";
and i need to have the output as $9
this works but its a bit too messy
for (int index = 0; index <= input.length() - 1; index ++)
{
if(String.valueOf(input.charAt(index)).matches("[^a-zA-Z\\s]"))
{
System.out.print(String.valueOf(input.charAt(index)));
}
}

The method matches returns a boolean. As you are trying to assign that to a String instead, you're getting the compilation error.

To solve your specific problem, you can use String.replaceAll, which takes a replacement regex:
String input = " This i$ an aaasdAr yeEeeAs oofo qwdsgy XY9 ";
String output = input.replaceAll("[a-zA-Z\\s]", "");
System.out.println(output);
This replaces everything that matches the regex with the empty string, and it prints $9.

Related

String buffer function setCharAt() throws error

I tried to run this code and remove all uppercase characters and print the changed string again. But all it does is throwing me a "cannot find symbol - method delete(int,int)" error in the String function. I'm pretty sure the loop variable is visible too.
String s = "Some Random Sentence Here";
int l = s.length()
for(int i = 0;i<l;i++)
{
char ch = s.charAt(i);
if(Character.isUpperCase(ch) == true)
{
s.delete(i,(i+2));
}
}
System.out.println(s);
Edit: Thanks Mentallurg, forgot the i less than l part
As stated in the comments there is no deletefunction for a string. String behaves a bit like a primitive type in Java but in the end not really.
Anyways you can solve the problem easy with streams as shown here:
String s1 = "Some Random Sentence Here";
s1=Arrays.stream(s1.split("")).map(x->(x.equals(x.toUpperCase())&&!x.equals(" "))?"":x).collect(Collectors.joining());
System.out.println(s1);
The problem is forgotten minus l when you remove this character :D
Use StringBuffer instead of String.
Use
i < l
Or
i <= l-1
Because the indexing starts with 0 and the the last element has index l-1.

Java: Removing duplicate words & substrings of words in java

Recently i have come up against a question which i am not able to tackle in school.
I need to remove duplicate words in an input string which consists of words. The main issue here is that the requirement states that i cannot use arrays or regular expressions.
E.g.
userInput = "this is a test testing is fun really fun"
the first "is" is a duplicate of "this" as it is a substring
the second "is" is a duplicate of the first "is"
"testing" is not a duplicate of "test" as it is not an exact match
therefore the output comes out as - "this a test testing fun really"
How would one actually achieve this without using Arrays or Regular Expressions as it is impossible to split the words up by the white spaces and dynamically create a String in java.
I didn't compile this code, but I think it should works.
Let me know if it can help you to solved your problem.
public String solve(String input) {
String ret = "";
int pos = 0;
while(pos<input.length()) {
// find next position of space
int next = input.indexOf(' ',pos);
// space not exists, skip next to end of string
if(next==-1) next = input.length();
// take 1 word from input
String word = input.substring(pos,next);
// check if word exists in previous result
if(ret.indexOf(word)==-1) {
if(ret.length() > 0) ret += " ";
// append word to ret
ret += word;
}
pos = next + 1;
}
return ret;
}

How to escape special characters from JSON when assign it to Java String

im tring to assign value from json to java String. but JSON value is including some special charactor ("\"). when i was try to assigen it to the string it gives error.
this is the JSON value,
"ValueDate":"\/Date(1440959400000+0530)\/"
this is how i trying to use it.
HistoryVO.setValueDate(DataUtil.getDateForUnixDate(historyJson.getString("ValueDate")));
or
Given that
I want ... to get [the] Date(1440959400000+0530) part,
I would use
String value = "/Date(1440959400000+0530)/";
int pos1 = value.indexOf("Date(");
if (pos1 > -1) {
int pos2 = value.indexOf(")", pos1);
if (pos2 > pos1) {
value = value.substring(pos1, pos2 + 1);
System.out.println(value);
}
}
Output is
Date(1440959400000+0530)
Note: This works by looking for "Date(" and then the next ")", and it removes everything not between those two patterns.
If you have specific character, ( and ), use substring method to get the value.
String value = "\\/Date(1440959400000+0530)\\/";
int start = value.indexOf("(");
int last = value.lastIndexOf("0");
value = value.substring(start + 1, last + 1);
System.out.println(value); <--- 1440959400000+0530
DataUtil.getDateForUnixDate(value);
I don't know DataUtil.getDateForUnixDate() method, but take care of + character because of it is not number string.
Update
To remove / character use replace method.
String value = "/Date(1440959400000+0530)/";
value = value.replace("/", "");
System.out.println(value);
output
Date(1440959400000+0530)
Mac,
As you asked for something like
String ValueDate = "\/Date(1440959400000+0530)\/";
The above one is not possible in java string, As it shows as invalid escape sequence, So replace the slash '\' as double slash '\' as below,
String ValueDate = "\\/Date(1440959400000+0530)\\/";
If am not clear of our question, pls describe it clearly
Regards,
Hari
i found the answer for my own question.
historyJson.getString("ValueDate");
this return the String like /Date(1440959400000+0530)/
now i can split it. thank you all for the help.
regards, macdaddy

Replace char at specific substring

first of all I want to say that I am kinda new to Java. So please be easy on me :)
I made this code, but I cannot find a way to change a character at a certain substring in my progress bar. What I want to do is this:
My progressbar is made out of 62 characters (including |). I want the 50th character to be changed into the letter B (uppercase).It should look something like this: |#########----B--|
I tried several things, but I dont know where to put the line of code to make this work. I tried using the substring and the replace code, but I can't find a way to make this work. Maybe I need to write my code in a different way to make this work? I hope someone can help me.
Thanks in advance!
int ecttotal = ectcourse1+ectcourse2+ectcourse3+ectcourse4+ectcourse5+ectcourse6+ectcourse7;
int ectmax = 60;
int ectavg = ectmax - ecttotal;
//Progressbar
int MAX_ROWS = 1;
for (int row = 1; row == MAX_ROWS; row++)
{
System.out.print("|");
for (int hash = 1; hash <= ecttotal; hash++)
System.out.print ("#");
for (int hyphen = 1; hyphen <= ectavg; hyphen++)
System.out.print ("-");
System.out.print("|");
}
System.out.println("");
System.out.println("");
}
Can you tell a little more what you want. Because what i sea it that, that you write some string into console. And is not way to change that what you already print to console.
Substring you can use only at String varibles.
If you want to change lettir with substring method in string varible try smth. like this:
String a="thi is long string try it";
if(a.length()>50){
a=a.substring(0,49)+"B"+a.substring(51);
}
Other way to change charater in string is to use string builder like this:
StringBuilder a= new StringBuilder("thi is long string try it");
a.setCharAt(50, 'B');
Sure you must first check the length of string to avoid the exceptions.
I hope that I helped you :)
Java StringBuilder has method setCharAt which can replace character at position with new character.
StringBuilder myName = new StringBuilder(<original string>);
myName.setCharAt(<position>, <character to replace>);
<position> starts with index 0
In your case:
StringBuilder myName = new StringBuilder("big longgggg string");
myName.setCharAt(50, 'B');
You can replace a certain index in a string by concatenating a new string around the intended index. For example the following code replaces the letter c with the letter X. Where 2 is the intended index to replace.
In other words, this code replaces the 3rd character in the string.
String s = "abcde";
s = s.substring(0, 2) + "X" + s.substring(3);
System.out.println(s);

String.split() Not Acting on Semicolon or Space Delimiters

This may be a simple question, but I have been Googling for over an hour and haven't found an answer yet.
I'm trying to simply use the String.split() method with a small Android application to split an input string. The input string will be something along the lines of: "Launch ip:192.168.1.101;port:5900". I'm doing this in two iterations to ensure that all of the required parameters are there. I'm first trying to do a split on spaces and semicolons to get the individual tokens sorted out. Next, I'm trying to split on colons in order to strip off the identification tags of each piece of information.
So, for example, I would expect the first round of split to give me the following data from the above example string:
(1) Launch
(2) ip:192.168.1.101
(3) port:5900
Then the second round would give me the following:
(1) 192.168.1.101
(2) 5900
However, the following code that I wrote doesn't give me what's expected:
private String[] splitString(String inputString)
{
String[] parsedString;
String[] orderedString = new String[SOSLauncherConstants.SOCKET_INPUT_STRING_PARSE_VALUE];
parsedString = inputString.trim().split("; ");
Log.i("info", "The parsed data is as follows for the initially parsed string of size " + parsedString.length + ": ");
for (int i = 0; i < parsedString.length; ++i)
{
Log.i("info", parsedString[i]);
}
for (int i = 0; i < parsedString.length; ++i )
{
if (parsedString[i].toLowerCase().contains(SOSLauncherConstants.PARSED_LAUNCH_COMMAND_VALUE))
{
orderedString[SOSLauncherConstants.PARSED_COMMAND_WORD] = parsedString[i];
}
if (parsedString[i].toLowerCase().contains("ip"))
{
orderedString[SOSLauncherConstants.PARSED_IP_VALUE] = parsedString[i].split(":")[1];
}
else if (parsedString[i].toLowerCase().contains("port"))
{
orderedString[SOSLauncherConstants.PARSED_PORT_VALUE] = parsedString[i].split(":")[1];
}
else if (parsedString[i].toLowerCase().contains("username"))
{
orderedString[SOSLauncherConstants.PARSED_USERNAME_VALUE] = parsedString[i].split(":")[1];
}
else if (parsedString[i].toLowerCase().contains("password"))
{
orderedString[SOSLauncherConstants.PARSED_PASSWORD_VALUE] = parsedString[i].split(":")[1];
}
else if (parsedString[i].toLowerCase().contains("color"))
{
orderedString[SOSLauncherConstants.PARSED_COLOR_VALUE] = parsedString[i].split(":")[1];
}
}
Log.i("info", "The parsed data is as follows for the second parsed string of size " + orderedString.length + ": ");
for (int i = 0; i < orderedString.length; ++i)
{
Log.i("info", orderedString[i]);
}
return orderedString;
}
For a result, I'm getting the following:
The parsed data is as follows for the parsed string of size 1:
launch ip:192.168.1.106;port:5900
The parsed data is as follows for the second parsed string of size 6:
launch ip:192.168.1.106;port:5900
192.168.1.106;port
And then, of course, it crashes because the for loop runs into a null string.
Side Note:
The following snippet is from the constants class that defines all of the string indexes --
public static final int SOCKET_INPUT_STRING_PARSE_VALUE = 6;
public static final int PARSED_COMMAND_WORD = 0;
public static final String PARSED_LAUNCH_COMMAND_VALUE = "launch";
public static final int PARSED_IP_VALUE = 1;
public static final int PARSED_PORT_VALUE = 2;
public static final int PARSED_USERNAME_VALUE = 3;
public static final int PARSED_PASSWORD_VALUE = 4;
public static final int PARSED_COLOR_VALUE = 5;
I looked into needing a possible escape (by inserting a \\ before the semicolon) on the semicolon delimiter, and even tried using it, but that didn't work. The odd part is that neither the space nor the semicolon function as a delimiter, yet the colon works on the second time around. Does anybody have any ideas what would cause this?
Thanks for your time!
EDIT: I should also add that I'm receiving the string over a WiFi socket connection. I don't think this should make a difference, but I'd like you to have all of the information that you need.
String.split(String) takes a regex. Use "[; ]". eg:
"foo;bar baz".split("[; ]")
will return an array containing "foo", "bar" and "baz".
If you need groups of spaces to work as a single delimiter, you can use something like:
"foo;bar baz".split("(;| +)")
I believe String.split() tries to split on each of the characters you specify together (or on a regex), not each character individually. That is, split(";.") would not split "a;b.c" at all, but would split "a;.b".
You may have better luck with Guava's Splitter, which is meant to be slightly less unpredictable than java.lang.String.split.
I would write something like
Iterable<String> splits = Splitter.on(CharMatcher.anyOf("; ")).split(string);
but Splitter also provides fluent-style customization like "trim results" or "skip over empty strings."
Is there a reason why you are using String.split(), but not using Regular Expressions? This is a perfect candidate for regex'es, esp if the string format is consistent.
I'm not sure if your format is fixed, and if it is, then the following regex should break it down for you (am sure that someone can come up with an even more elegant regex). If you have several command strings that follow, then you can use a more flexible regex and loop over all the groups:
Pattern p = Pattern.compile("([\w]*)[ ;](([\w]*):([^ ;]*))*");
Matcher m = p.match( <input string>);
if( m.find() )
command = m.group(1);
do{
id = m.group(3);
value = m.group(4);
} while( m.find() );
A great place to test out regex'es online is http://www.regexplanet.com/simple/index.html. It allows you to play with the regex without having to compile and launch you app every time if you just want to get the regex correct.

Categories