I have an overriding method with String which returns String in format of:
"abc,cde,def,fgh"
I want to split the string content into two parts:
String before first comma and
String after first comma
My overriding method is :
#Override
protected void onPostExecute(String addressText) {
placeTitle.setText(addressText);
}
Now how do I split the string into two parts, so that I can use them to set the text in two different TextView?
You may use the following code snippet
String str ="abc,cde,def,fgh";
String kept = str.substring( 0, str.indexOf(","));
String remainder = str.substring(str.indexOf(",")+1, str.length());
String splitted[] =s.split(",",2); // will be matched 1 times.
splitted[0] //before the first comma. `abc`
splitted[1] //the whole String after the first comma. `cde,def,fgh`
If you want only cde as the string after first comma.
Then you can use
String splitted[] =s.split(",",3); // will be matched 2 times
or without the limit
String splitted[] =s.split(",");
Don't forget to check the length to avoid ArrayIndexOutOfBound.
The below is what you are searching for:
public String[] split(",", 2)
This will give 2 string array. Split has two versions. What you can try is
String str = "abc,def,ghi,jkl";
String [] twoStringArray= str.split(",", 2); //the main line
System.out.println("String befor comma = "+twoStringArray[0]);//abc
System.out.println("String after comma = "+twoStringArray[1]);//def,ghi,jkl
String s =" abc,cde,def,fgh";
System.out.println("subString1="+ s.substring(0, s.indexOf(",")));
System.out.println("subString2="+ s.substring(s.indexOf(",") + 1, s.length()));
// Note the use of limit to prevent it from splitting into more than 2 parts
String [] parts = s.split(",", 2);
// ...setText(parts[0]);
// ...setText(parts[1]);
For more information, refer to this documentation.
Use split with regex:
String splitted[] = addressText.split(",",2);
System.out.println(splitted[0]);
System.out.println(splitted[1]);
:In this case you can use replaceAll with some regex to get this input so you can use :
System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));
If the key is just an String you can use (\\D?),.*
System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));
From jse1.4String - Two split methods are new. The subSequence method has been added, as required by the CharSequence interface that String now implements. Three additional methods have been added: matches, replaceAll, and replaceFirst.
Using Java String.split(String regex, int limit) with Pattern.quote(String s)
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
String str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
String quotedText = Pattern.quote( "?" );
// ? - \\? we have to escape sequence of some characters, to avoid use Pattern.quote( "?" );
String[] split = str.split(quotedText, 2); // ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz"]
for (String string : split) {
System.out.println( string );
}
I have face the same problem in URL parameters, To resoleve it i need to split based on first ? So that the remaing String contains parameter values and they need to be split based on &.
String paramUrl = "https://www.google.co.in/search?q=encode+url&oq=encode+url";
String subURL = URLEncoder.encode( paramUrl, "UTF-8");
String myMainUrl = "http://example.com/index.html?url=" + subURL +"&name=chrome&version=56";
System.out.println("Main URL : "+ myMainUrl );
String decodeMainURL = URLDecoder.decode(myMainUrl, "UTF-8");
System.out.println("Main URL : "+ decodeMainURL );
String[] split = decodeMainURL.split(Pattern.quote( "?" ), 2);
String[] Parameters = split[1].split("&");
for (String param : Parameters) {
System.out.println( param );
}
Run Javascript on the JVM with Rhino/Nashorn « With JavaScript’s String.prototype.split function:
var str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
var parts = str.split(',');
console.log( parts ); // (5) ["abc?def", "ghi?jkl", "mno", "pqr?stu", "vwx?yz"]
console.log( str.split('?') ); // (5) ["abc", "def,ghi", "jkl,mno,pqr", "stu,vwx", "yz"]
var twoparts = str.split(/,(.+)/);
console.log( parts ); // (3) ["abc?def", "ghi?jkl,mno,pqr?stu,vwx?yz", ""]
console.log( str.split(/\?(.+)/) ); // (3) ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz", ""]
public static int[] **stringToInt**(String inp,int n)
{
**int a[]=new int[n];**
int i=0;
for(i=0;i<n;i++)
{
if(inp.indexOf(",")==-1)
{
a[i]=Integer.parseInt(inp);
break;
}
else
{
a[i]=Integer.parseInt(inp.substring(0, inp.indexOf(",")));
inp=inp.substring(inp.indexOf(",")+1,inp.length());
}
}
return a;
}
I created this function. Arguments are input string (String inp, here) and integer value(int n, here), which is the size of an array which contains values in string separated by commas. You can use other special character to extract values from string containing that character. This function will return array of integer of size n.
To use,
String inp1="444,55";
int values[]=stringToInt(inp1,2);
Related
String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
for (String opElement : operatorList) {
if (originalString.contains(opElement)) {
String tempStr = originalString.replace(opElement, "user." + opElement);
originalString = tempStr;
}
}
System.out.println("originalString " + originalString);
Output:
user.city=Houston^ORlast_user.name=Cervantsz^ORfirst_user.name=John^user.name=don
When i am trying to replace name with "user.name" at that time name from "last_name" is replaced with "last_user.name" and first_name with first_user.name
But i want replace "name" with "user.name" and "last_name" with "user.last_name"
and "first_name" with "user.first_name".
Any help appreciated.
You can add prefix all key and control that key. Example
String[] operatorList = {"name", "first_name", "last_name", "city"};
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^ORname=don";
for (String opElement : operatorList) {
if (originalString.contains("^OR"+opElement)) {
String tempStr = originalString.replace(opElement, "user." + opElement);
originalString = tempStr;
}
}
System.out.println("originalString " + originalString);
If the values you are trying to change are always unique and generated (meaning they are always in the same order), you can simply put your operators in the same order and use replaceLast() instead.
A more complete solution would be to determine how the string is constructed. Do all the values have a ^ in front of them? Is OR generated for the same values or is it to indicate optional values?. So in the end, what allows you to split the string properly. Then you can use a Regex to use the surrounding characters.
I would format the string to make sure the splitters are constant (all "^OR" become "##%!!" and all remaining "^" become "%!!") so all replaced strings start with !!. Then I would reformat the string to the original format using the remaining "##%" or "%" :
String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll("\\^OR", "##%!!");
originalString = originalString.replaceAll("\\^", "%!!");
//the order is important here
for (String opElement : operatorList) {
if (originalString.startsWith(opElement)) {
originalString = originalString.replaceFirst(opElement, "user." + opElement);
}
originalString = originalString.replaceAll("!!" + opElement, "user." + opElement);
// no need for an other alternative here because replaceAll returns the
// String as is if it does not find the first parameter in the String.
}
originalString = originalString.replaceAll("##%", "^OR");
originalString = originalString.replaceAll("%", "^");
// the order here is also important
outputs : "user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don"
If all keypairs need prefix "user.", I would like to split originalString first.
In Java8
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
String[] params = originalString.split("\\^");
String result = String.join("^", Arrays.stream(params)
.map(param -> param.startsWith("OR") ? "ORuser." + param.substring(2) : "user." + param)
.collect(Collectors.toList()));
System.out.println(result);
It can also be changed to for loop type.
You may use a quick search and replace with an alternation based pattern created dynamically from the search words only when they are preceded with a word boundary or ^ + OR/AND/etc. operators and followed with a word boundary. Note that this solution assumes the search words only consist of word chars (letters, digits or _):
String[] operatorList = { "name", "first_name", "last_name", "city" };
// assuming operators only consist of word chars
String pat = "(\\b|\\^(?:OR|AND)?)(" + String.join("|", operatorList) + ")\\b";
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll(pat, "$1user.$2");
System.out.println(originalString);
// => user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don
See the Java demo online
The regex will look like
(\b|\^(?:OR|AND)?)(name|first_name|last_name|city)\b
See the regex demo.
Details
(\b|\^(?:OR|AND)?) - Group 1: a word boundary \b or a ^ symbol and an optional substring, OR or AND (you may add more here after |)
(name|first_name|last_name|city) - Group 2: any of the search words
\b - a trailing word boundary.
The $1 in the replacement pattern inserts the contents of Group 1 and $2 does the same with Group 2 contents.
I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
I can have this string as below :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
or
String s = "chapterId=c_1§ionId=s_24666";
I need to get the number ("24666" in the examples).
String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks
You can use regExp
String s = "chapterId=c_1§ionId=s_24666";
//OR
//String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*?s_(\\d+).*","$1");
System.out.println(s);
OUTPUT:
24666
Where,
.*?s_ means anything before s_ (s_ inclusive)
(\\d+) means one or more digits () used for group
$1 means group 1 which is digits after s_
Note:Assumed that your every string follows specific format which includes s_ and number after s_.
You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.
Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String[] params = s.split("&");
for (String param : params) {
String[] nameValue = param.split("=");
if ("sectionId".equals(nameValue[0])) {
int number = Integer.parseInt(nameValue[1].substring(2));
System.out.println(number); // Prints 24666
// If you don't care about other parameters, this will skip the rest:
break;
}
}
Note:
You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:
try {
int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
// Invalid parameter value, not the expected format!
}
Try this:
I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.
Code:
String s = "chapterId=c_1§ionId=s_**24666**";
int endIndex = s.indexOf("&isHL");
String answer = s.substring(s.lastIndexOf("s_") + 2, endIndex == -1 ? s.length() : endIndex);
Try following:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String tok[]=s.split("&");
for(String test:tok){
if(test.contains("s_")){
String next[]=test.split("s_");
System.out.println(next[1]);
}
}
Output :
24666
Alternatively you can simply remove all other words if they are not required as below
String s="chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);
Output :
24666
The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.
You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.
demo here
Following code will work even if there is multiple occurrence of integer in given string
String inputString = "chapterId=c_a§ionId=s_24666&isHL=1&cssFileName=haynes_45";
String[] inputParams = inputString.split("&");
for (String param : inputParams)
{
String[] nameValue = param.split("=");
try {
int number = Integer.parseInt(getStringInt(nameValue[1]));
System.out.println(number);
}
catch(IllegalStateException illegalStateException){
}
}
private String getStringInt(String inputString)
{
Pattern onlyInt = Pattern.compile("\\d+");
Matcher matcher = onlyInt.matcher(inputString);
matcher.find();
String inputInt = matcher.group();
return inputInt;
}
OUTPUT
2466
1
45
Use split method as
String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");
Now to get your desire number you just need to do
String finalResult = result3[1];
INPUT :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
OUPUT :
24666
I'm not strong in regex, so any help would be appreciated.
I need to parse such strings:
["text", "text", ["text",["text"]],"text"]
And output should be (4 strings):
text, text, ["text",["text"]], text
I've tried this pattern (\\[[^\\[,^\\]]*\\])|(\"([^\"]*)\"):
String data="\"aa\", \"aaa\", [\"bb\", [\"1\",\"2\"]], [cc]";
Pattern p=Pattern.compile("(\\[[^\\[,^\\]]*\\])|(\"([^\"]*)\")");
But output is (quotes themselves in output are not so critical):
"aa", "aaa", "bb", "1", "2", [cc]
How to improve my regex?
I'm not sure regex are able to do that kind of stuff on their own. Here is a way to do it though:
// data string
String input = "\"aa\", \"a, aa\", [\"bb\", [\"1\", \"2\"]], [cc], [\"dd\", [\"5\"]]";
System.out.println(input);
// char that can't ever be within the data string
char tempReplacement = '#';
// escape strings containing commas, e.g "hello, world", ["x, y", 42]
while(input.matches(".*\"[^\"\\[\\]]+,[^\"\\[\\]]+\".*")) {
input = input.replaceAll("(\"[^\"\\[\\]]+),([^\"\\[\\]]+\")", "$1" + tempReplacement + "$2");
}
// while there are "[*,*]" substrings
while(input.matches(".*\\[[^\\]]+,[^\\]]+\\].*")) {
// replace the nested "," chars by the replacement char
input = input.replaceAll("(\\[[^\\]]+),([^\\]]+\\])", "$1" + tempReplacement + "$2");
}
// split the string by the remaining "," (i.e. those non nested)
String[] split = input.split(",");
List<String> output = new LinkedList<String>();
for(String s : split) {
// replace all the replacement chars by a ","
s = s.replaceAll(tempReplacement + "", ",");
s = s.trim();
output.add(s);
}
// syso
System.out.println("SPLIT:");
for(String s : output) {
System.out.println("\t" + s);
}
Output:
"aa", "a, aa", ["bb", ["1", "2"]], [cc], ["dd", ["5"]]
SPLIT:
"aa"
"a, aa"
["bb", ["1","2"]]
[cc]
["dd", ["5"]]
PS: the code seems complex 'cause commented. Here is a more concise version:
public static List<String> split(String input, char tempReplacement) {
while(input.matches(".*\"[^\"\\[\\]]+,[^\"\\[\\]]+\".*")) {
input = input.replaceAll("(\"[^\"\\[\\]]+),([^\"\\[\\]]+\")", "$1" + tempReplacement + "$2");
}
while(input.matches(".*\\[[^\\]]+,[^\\]]+\\].*")) {
input = input.replaceAll("(\\[[^\\]]+),([^\\]]+\\])", "$1" + tempReplacement + "$2");
}
String[] split = input.split(",");
List<String> output = new LinkedList<String>();
for(String s : split) {
output.add(s.replaceAll(tempReplacement + "", ",").trim());
}
return output;
}
Call:
String input = "\"aa\", \"a, aa\", [\"bb\", [\"1\", \"2\"]], [cc], [\"dd\", [\"5\"]]";
List<String> output = split(input, '#');
It seems that you have recursion in your input, so if you have many nested [] regexes are probably not the best solution.
For this purpose I think it's far better/easier to use simple algorithm using indexOf() and substring(). It's also aften more efficient!
Unfortunately i don't think you can do that with Java regexes. What you have here is recursive expression.. This type of language is not amendable to basic regular expressions (which is what java Pattern actually is).
But it's not that hard to write a small recursive descent parser for that language.
You can check to following answer for inspiration: java method for parsing nested expressions
I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();