Hi I have a question about how to get only part of given string :
String = "1. Name:Tom\tNumber:123";
in this case I would like to get only part with name ( "Tom" )
Is there is any solution to do it?
Thank's for help
This is a simple way assuming the format won't change.
int start = yourString.indexOf(':') + 1; //get character after this
int end = yourString.indexOf('\t');
String result = yourString.substring(start,end);
You can also write your own regex to match this.
If that format is how it always shows up this would work:
String str = "1. Name:Tom\tNumber:123";
String tom = str.substring(str.indexOf(':')+1, str.indexOf('\t'));
Using the first occurrence of : and the \t allows you to parse out the name. In the case of your :, you want to begin your string 1 character ahead.
Result:
Tom
What you need, you will easyly find at the String documentation.
Related
As the title of the question states: How can I remove , Null(""), from the String?
I have tried the following code, but it is not working:
String c = "customer_date, privacy_code, Null(""), ";
String nd = "Null(\"\")";
c = c.substring(0, c.lastIndexOf(nd));
If you want to remove it only from the end of the string, you can use String#replaceAll:
nd = nd.replaceAll("Null\\(\"\"\\),$", "");
Since it accepts a regex, I added the $ special character that matches the end of a string.
Please visit the String API to discover many useful methods that will help you.
Your code does not compile if you don't use escape character , any way you dont have to trouble your self with quotes you can only String nd = "Null"; instead like so
String c="customer_date, privacy_code, Null(\"\"), ";
String nd = "Null";
c=c.substring(0,c.lastIndexOf(nd));
System.out.println(c);
because a piece of string youre trying to remove starts with NULL anyway
I like using a sledgehammer to crack a nut!
String in = "customer_date, privacy_code, Null(\"\"), ";
String out = Arrays.asList(in.split(",")).stream()
.map(String::trim)
.filter(s -> !s.equals("Null(\"\")"))
.collect(Collectors.joining(", "));
I am trying to convert all links in a given string to clickable a tags using the following code :
String [] parts = comment.split("\\s");
String newComment=null;
for( String item : parts ) try {
URL url = new URL(item);
// If possible then replace with anchor...
if(newComment==null){
newComment=""+ url + " ";
}else{
newComment=newComment+""+ url + " ";
}
} catch (MalformedURLException e) {
// If there was an URL that was not it!...
if(newComment==null){
newComment = item+" ";
}else{
newComment = newComment+item+" ";
}
}
It works fine for
Hi there, click here http://www.google.com ok?
converting it to
Hi there, click here http://www.google.com ok?
But when the string is this :
Hi there, click
here http://www.google.com
ok?
its still converting it to :
Hi there, click here http://www.google.com ok?
Whereas I want the final result to be :
Hi there, click
here http://www.google.com
ok?
I think its including the newline character also while making the split.
How do I preserve the newline character in this case ?
I would suggest a different approach:
String noNewLines = "Hi there, click here http://www.google.com ok?";
String newLines = "Hi there, \r\nclick here \nhttp://www.google.com ok?";
// This is a String format with two String variables.
// They will be replaced with the desired values once the "format" method is called.
String replacementFormat = "%s";
// The first round brackets define a group with anything starting with
// "http(s)". The second round brackets delimit that group by a lookforward reference
// to whitespace.
String pattern = "(http(s)?://.+?)(?=\\s)";
noNewLines = noNewLines.replaceAll(
pattern,
// The "$1" literals are group back-references.
// In our instance, they reference the group enclosed between the first
// round brackets in the "pattern" String.
new Formatter().format(replacementFormat, "$1", "$1")
.toString()
);
System.out.println(noNewLines);
System.out.println();
newLines = newLines.replaceAll(
pattern,
new Formatter().format(replacementFormat, "$1", "$1")
.toString()
);
System.out.println(newLines);
Output:
Hi there, click here http://www.google.com ok?
Hi there,
click here
http://www.google.com ok?
This will replace all your http(s) links to an anchor reference, whether or not you have newlines (windows or *nix) in your text.
Edit
For best coding practices you should set the replacementFormat and pattern variables as constants (so, final static String REPLACEMENT_FORMAT and so on).
Edit II
Actually grouping the URl pattern isn't really necessary, as the whitespace lookahead is sufficient. But well, I'm leaving it as is, it works.
You could just use
String [] parts = comment.split("\\ ");
instead of
String [] parts = comment.split("\\s");
as eldris said, "\s" is for every white-space character, so "\ ", for just the space character itself should do for you.
I would suggest following solution to your problem:
First split by new line character
For each line do processing that you have mentioned above
Add all processed lines
That ways new line character will be retained and also you will be able to do in each line what you are currently doing.
Hope this helps.
Cheers !!
I'd like to parse a string in order to see if it matches the entire string or a substring.
I tried this:
String [] array = {"Example","hi","EXAMPLE","example","eXamPLe"};
String word;
...
if ( array[j].toUpperCase().contains(word) || array[j].toLowerCase().contains(word) )
System.out.print(word + " ");
But my problem is:
When user enter the word "Example" (case sensitive) and in my array there is "Example" it doesn't print it, it only prints "EXAMPLE" and "example" that's because when my program compares the two strings it converts my array[j] string to uppercase or lowercase so it won't match words with both upper and lower cases like the word "Example".
So in this case if user enters "Examp" I want it to print:
Example EXAMPLE example eXamPLe
You can convert both the input string and the candidates to uppercase before calling contains().
if ( array[j].toUpperCase().contains( word.toUpperCase() ) ) {
System.out.print(word + " ");
}
If you are just looking for full matches, use equalsIgnoreCase.
When partial match is needed you might need a trie or something similar.
Compare to the same case of word.
if ( array[j].toUpperCase().contains(word.toUpperCase()))
{
}
You are looking for this:
if (array[j].toUpperCase().contains(word.toUpperCase())) {
System.out.print(array[j]+ " ");
}
This will print:
Example EXAMPLE example eXamPLe
As you wanted!
well, i think othehan using .equalsIgnoreCase u might also be interested in the Matcher( Java Regex). the links are self-explanaory: http://www.vogella.com/articles/JavaRegularExpressions/article.html
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html
Pattern/Matcher group() to obtain substring in Java?
String contains - ignore case
Submit this as your assignment. You'll definitely come off as unique.
String word = "Exam";
String [] array = {"Example","hi","EXAMPLE","example","eXamPLe"};
for (String str : array)
if (str.matches("(?i)"+word+".*"))
System.out.print(str + " "); // prints: Example EXAMPLE example eXamPLe
I have a string like delivery:("D1_0"), how do i get the value inside the quotes alone from it. i.e D1_0 alone from it.
You could use regualr expresion like \"(.*?)\" to find that group, or even better, iterate over your String looking for quote marks " and reading characters inside of them until you find another quote mark. Something similar to this.
Try this
int i = stringvariable.indexOf("(");
int j = stringvariable.indexOf(")");
String output = stringvariable.substring(i+2, j-2);
You will get the required value in output variable.
If your string is constant, in that the beginning of the string will not change, you could use the slice function
In Javascript:
var text='delivery:("D1_0")';
alert(text.slice(11, 15)); //returns "D1_0"
In Java:
String text = "delivery:(\"D1_0\")";
String extract = text.substring(11, 15);
Use:
String str = "delivery:(\"D1_0\")";
String arr[] = str.split("[:\"()]"); //you will get arr[delivery, , , D1_0], choose arr[3]
System.out.println(arr[3]);
"If your String is always in this format you can use
String theString = "delivery:(\"D1_0\")";
String array[] = theString.split("\"");
String result = array[1]; // now result string is D1_0
// Note: array[0] contains the first part(i.e "delivery:(" )
// and array[2] contains the second (i.e ")" )
i have a string:
String value = "(name) Says: hello (/name)";
where "name" could also be "lastName", "address" "postalCode" or many many other things.
i split the string on the "("
i want to also split on the ")" ... however, some strings will only contain the following:
String value = "(name Says: hello (/name)";
my problem is that the string content could also contain ")" and "(" so how would i parse this then? For instance:
String value = "(name Says: can you solve for y = (x-b)? (/name)";
the string could also be as follows:
String value = "(name)Says: can you solve for y = (x-b)? (/name)";
OR
String value = "(name) Says: can you solve for y = (x-b)?(/name)";
OR
String value = "(name)Says: can you solve for y = (x-b)?(/name)";
i was initially thinking that i could do a count of how many ")" there are in a string. However, if there are more than 2, i'm not sure what i should do? The reason why i would need to know how many ")" there are in a string is because i want to isolate "name"
any ideas? (i don't want to use any libraries, just want to come up with the logic )...
The question wasn't very clear to me. However,as far as I could understand,I guess that you want to capture the name and also the sentence that follows it,both seperately.Please correct me if I am wrong.
Here's the solution:
1.Parse your String until the first space after "(" .
2.Store it in a temp String. Its length is given by temp.length().
3.So check if temp.charAt(temp.length()-1)==')'.
4.If yes then name would be in the substring temp.substring(1,temp.length()-2).
5.Otherwise it would be in the substring temp.substring(1,temp.length()-1).
6.Now the value after name can be stored in another String until you find "(/".
Hope it helps.
Extract all characters after the first space and before the last space.
below code will return name in both of your condition:
String s = "(name Says: can you solve for y = (x-b)? (/name)";
int firstIndex = s.indexOf("(");
int secondIndex = s.indexOf(":");
int thirdIndex = 0;
String name = "";
if(s.substring(firstIndex, secondIndex).contains(")")) {
thirdIndex = s.indexOf(")");
} else {
thirdIndex = s.indexOf(" ");
}
System.out.println("(name) or (name : "+s.substring(firstIndex+1, thirdIndex));
String temp = s.substring(thirdIndex+1, s.length());
System.out.println(temp.substring(0, temp.indexOf("(/")));
System.out.println("(/name) : "+ temp.substring(temp.indexOf("(/")+2, temp.lastIndexOf(")")));
First parse last symbols while you will not find "(/string)"
Then get all that you have between "(/" and ")" except spaces at the edges.
And try to find in the beginning of the line kind of this construction "(" + name.trim() + ")" with or without ")"
Besides java.util.regex.* must be your best friend in this situation.