Read text from a string & edit it - java

Maybe there is already a similar question, but I didn't find it.
So, how can I "read" a string and edit it? For example:
String exampleString = "Monday: Do stuff & things!";
Now, I want to "read and edit" the string, so I get this:
String exampleString = "Do stuff & things!";
Is there a way to edit a string?
Kind regards!

Try this
Examplestring.split(":")[1]
You will get you desired o/p
Better go through java string basics

Use substring() or split() method :
public static void main(String[] args) {
String exampleString = "Monday: Do stuff & things!";
String editedString=exampleString.substring(exampleString.indexOf(":")+1);
System.out.println("Edited String :"+editedString);
//OR
String []edited=exampleString.split(":", 2);
System.out.println("Edited String :"+edited[1]);
}
}

Related

How can I parse a specific cookie from this string in Java?

say I have the following string in a variable
cookie-one=someValue;HttpOnly;Secure;Path=/;SameSite=none, cookie-two=someOtherValue;Path=/;Secure;HttpOnly, cookie-three=oneMoreValue;Path=/;Secure
and I want a substring from the name of a cookie that I choose say cookie-two and store the string up to the contents of that cookie.
So basically I need
cookie-two=someOtherValue;Path=/;Secure;HttpOnly
How can I get this substring out?
You can just separate the String by commas first to separate the cookies. For example if you wanted just the cookie that has the name cookie-two:
String s = "cookie-one=someValue;HttpOnly;Secure;Path=/;SameSite=none, cookie-two=someOtherValue;Path=/;Secure;HttpOnly, cookie-three=oneMoreValue;Path=/;Secure";
String[] cookies = s.split(",");
for(String cookie : cookies){
if(cookie.trim().startsWith("cookie-two")){
System.out.println(cookie);
}
}
This is possible to achieve in several different ways depending on how the data might vary in the sting. For your specific example we could for instance do like this:
String cookieString = "cookie-one=someValue;HttpOnly;Secure;Path=/;SameSite=none, cookie-two=someOtherValue;Path=/;Secure;HttpOnly, cookie-three=oneMoreValue;Path=/;Secure";
String result = "";
for(String s: cookieString.split(", ")) {
if(s.startsWith("cookie-two")) {
result = s;
break;
}
}
We could also use regex and/or streams to make the code look nicer, but this is probably one of the most straight forward ways of achieving what you want.

Easiest way to do this : Put a String into the middle of a String for various lengths

Trying to split a String in certain ways without changing the
String(String embed, String payload)
structure.
System.out.println(embedCenter("<<>>", "Yay")); // => <<Yay>>
This is how it should look, so putting "<<>>" for embed and "Yay" for payload should return <<Yay>>, however for "()" embed and "Yay" Payload it should return "(Yay)" and for ":-)" embed and "Yay" payload it should return ":Yay-)"
So I'm just starting to learn, and kinda stuck at this question - I've tried doing substrings but while I could get one of those results, I cant find a way to get all of them with the same method.
public static String embedCenter(String embed, String payload) {
return ""; //
}
public static void main(String[] args) {
System.out.println(embedCenter("<<>>", "Yay")); // => <<Yay>>
System.out.println(embedCenter("()", "Yay")); // => (Yay)
System.out.println(embedCenter(":-)", "Example")); // :Example-)
Ok, I did it, I thought way too complicated, did it really easy simply by dividing the String with length()/2, perfectly worked. Thanks for the input!
int length = embed.length();
String subembed = embed.substring(0,embed.length()/2);
String finembed = embed.substring(embed.length()/2);
return subembed + payload + finembed;

how to split string using comma but ignore on certain condition?

I want to split below string
{"address":"XXXXXX","amount":"0.25"},{"address":"AAAAAA","amount":"0.25"}
into two values
{"address":"XXXXXX","amount":"0.25"}
{"address":"AAAAAA","amount":"0.25"}
It is not a recommended thing to parse json the way you are doing but in case you really wanna just split, you can do so using lookarounds using regex. Here is the java code for same.
public static void main(String args[]) throws Exception {
String s = "{\"address\":\"XXXXXX\",\"amount\":\"0.25\"},{\"address\":\"AAAAAA\",\"amount\":\"0.25\"}";
String[] data = s.split("(?<=\\}),(?=\\{)");
Arrays.asList(data).forEach(System.out::println);
}
Prints,
{"address":"XXXXXX","amount":"0.25"}
{"address":"AAAAAA","amount":"0.25"}

Java String Limit

I am new to java (previously only worked with sql) and I am attempting to set a length limit for my string variable. Basically I have a username field that can only be 6 characters long.
I am trying the following:
private String username (6);
I am assuming this is not the correct format. Does anyone know how i can do this in java correctly?
Some other answers have claimed that "There is no way to limit Strings in java to a certain finite number through inbuilt features", and suggested rolling ones own. However, Java EE validations API is meant for just this. An example:
import javax.validation.constraints.Size;
public class Person {
#Size(max = 6)
private String username;
}
Further info on how to use Validation API, see this thread for example. Hibernate validator is the reference implementation (usage).
In short, when annotating an object as #Valid, validations done in annotations will be enforced.
There is no way to limit Strings in java to a certain finite number through inbuilt features. Strings are immutable and take the value that you provide in their constructor. You will need to write code manually to do this.
Use the length() function to determine the length of the String and do not allow lengths greater than 6.
if( username.length() > 6 )
{
throw new RuntimeException("User name too long");
}
One of the options you have is to throw an exception and then handle it elsewhere. Or you can display an alert to the user immediately after you encounter the problem.
What you suggested is not the correct way to do what you want. Try using:
private int stringLimit = 6;
// Take input from user
private String username = inputString.substring(0,stringLimit);
For example:
inputString = "joelspolsky";
private String username = inputString.substring(0,stringLimit);
// username is "joelsp"
You can try soemthing like this:Take input from user then validate that string by using following function.
String output ="";
public boolean set(String str, int limit){
if(str.length() <= limit){
output= str;
return true;
}
else
return false;
}
SubString() won't be suitable for this. If the length of input string is less than limit StringIndexOutOfBoundsException will be thrown.
I think you can use StringBuilder for this.
StringBuilder buider = new StringBuilder(username);
builder.setLength(6);
String restName = builder.toString().trim();
In this case annotation mechanism can be useful, if, of course, you know what this is.
You can create your own annotation, something like:
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
public #interface MaxLength {
int value();
}
And use it like:
#MaxLength(6)
private String username;
Then you have to post-process such objects in a special post-processor, which you have to create manually.
example to cut the length of URL
if (getURLitem.length() >= 15) {
int stringLimit = 15;
final String smallURL = getURLitem.substring(0, stringLimit);
//show short string in textview...
TextView urlLink = (TextView) findViewById(R.id.url_link);
urlLink.setText(smallURL);
// Set On click listener and open URL below
...........
} else {
//show full string in textview...
TextView urlLink = (TextView) findViewById(R.id.url_link);
urlLink.setText(getURLitem);
// Set On click listener and open URL below
...........
}

How to replace tokens in a string without StringTokenizer

Given a string like so:
Hello {FIRST_NAME}, this is a personalized message for you.
Where FIRST_NAME is an arbitrary token (a key in a map passed to the method), to write a routine which would turn that string into:
Hello Jim, this is a personalized message for you.
given a map with an entry FIRST_NAME -> Jim.
It would seem that StringTokenizer is the most straight forward approach, but the Javadocs really say you should prefer to use the regex aproach. How would you do that in a regex based solution?
Thanks everyone for the answers!
Gizmo's answer was definitely out of the box, and a great solution, but unfortunately not appropriate as the format can't be limited to what the Formatter class does in this case.
Adam Paynter really got to the heart of the matter, with the right pattern.
Peter Nix and Sean Bright had a great workaround to avoid all of the complexities of the regex, but I needed to raise some errors if there were bad tokens, which that didn't do.
But in terms of both doing a regex and a reasonable replace loop, this is the answer I came up with (with a little help from Google and the existing answer, including Sean Bright's comment about how to use group(1) vs group()):
private static Pattern tokenPattern = Pattern.compile("\\{([^}]*)\\}");
public static String process(String template, Map<String, Object> params) {
StringBuffer sb = new StringBuffer();
Matcher myMatcher = tokenPattern.matcher(template);
while (myMatcher.find()) {
String field = myMatcher.group(1);
myMatcher.appendReplacement(sb, "");
sb.append(doParameter(field, params));
}
myMatcher.appendTail(sb);
return sb.toString();
}
Where doParameter gets the value out of the map and converts it to a string and throws an exception if it isn't there.
Note also I changed the pattern to find empty braces (i.e. {}), as that is an error condition explicitly checked for.
EDIT: Note that appendReplacement is not agnostic about the content of the string. Per the javadocs, it recognizes $ and backslash as a special character, so I added some escaping to handle that to the sample above. Not done in the most performance conscious way, but in my case it isn't a big enough deal to be worth attempting to micro-optimize the string creations.
Thanks to the comment from Alan M, this can be made even simpler to avoid the special character issues of appendReplacement.
Well, I would rather use String.format(), or better MessageFormat.
String.replaceAll("{FIRST_NAME}", actualName);
Check out the javadocs for it here.
Try this:
Note: The author's final solution builds upon this sample and is much more concise.
public class TokenReplacer {
private Pattern tokenPattern;
public TokenReplacer() {
tokenPattern = Pattern.compile("\\{([^}]+)\\}");
}
public String replaceTokens(String text, Map<String, String> valuesByKey) {
StringBuilder output = new StringBuilder();
Matcher tokenMatcher = tokenPattern.matcher(text);
int cursor = 0;
while (tokenMatcher.find()) {
// A token is defined as a sequence of the format "{...}".
// A key is defined as the content between the brackets.
int tokenStart = tokenMatcher.start();
int tokenEnd = tokenMatcher.end();
int keyStart = tokenMatcher.start(1);
int keyEnd = tokenMatcher.end(1);
output.append(text.substring(cursor, tokenStart));
String token = text.substring(tokenStart, tokenEnd);
String key = text.substring(keyStart, keyEnd);
if (valuesByKey.containsKey(key)) {
String value = valuesByKey.get(key);
output.append(value);
} else {
output.append(token);
}
cursor = tokenEnd;
}
output.append(text.substring(cursor));
return output.toString();
}
}
With import java.util.regex.*:
Pattern p = Pattern.compile("{([^{}]*)}");
Matcher m = p.matcher(line); // line being "Hello, {FIRST_NAME}..."
while (m.find) {
String key = m.group(1);
if (map.containsKey(key)) {
String value= map.get(key);
m.replaceFirst(value);
}
}
So, the regex is recommended because it can easily identify the places that require substitution in the string, as well as extracting the name of the key for substitution. It's much more efficient than breaking the whole string.
You'll probably want to loop with the Matcher line inside and the Pattern line outside, so you can replace all lines. The pattern never needs to be recompiled, and it's more efficient to avoid doing so unnecessarily.
The most straight forward would seem to be something along the lines of this:
public static void main(String[] args) {
String tokenString = "Hello {FIRST_NAME}, this is a personalized message for you.";
Map<String, String> tokenMap = new HashMap<String, String>();
tokenMap.put("{FIRST_NAME}", "Jim");
String transformedString = tokenString;
for (String token : tokenMap.keySet()) {
transformedString = transformedString.replace(token, tokenMap.get(token));
}
System.out.println("New String: " + transformedString);
}
It loops through all your tokens and replaces every token with what you need, and uses the standard String method for replacement, thus skipping the whole RegEx frustrations.
Depending on how ridiculously complex your string is, you could try using a more serious string templating language, like Velocity. In Velocity's case, you'd do something like this:
Velocity.init();
VelocityContext context = new VelocityContext();
context.put( "name", "Bob" );
StringWriter output = new StringWriter();
Velocity.evaluate( context, output, "",
"Hello, #name, this is a personalized message for you.");
System.out.println(output.toString());
But that is likely overkill if you only want to replace one or two values.
import java.util.HashMap;
public class ReplaceTest {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("FIRST_NAME", "Jim");
map.put("LAST_NAME", "Johnson");
map.put("PHONE", "410-555-1212");
String s = "Hello {FIRST_NAME} {LAST_NAME}, this is a personalized message for you.";
for (String key : map.keySet()) {
s = s.replaceAll("\\{" + key + "\\}", map.get(key));
}
System.out.println(s);
}
}
The docs mean that you should prefer writing a regex-based tokenizer, IIRC. What might work better for you is a standard regex search-replace.
Generally we'd use MessageFormat in a case like this, coupled with loading the actual message text from a ResourceBundle. This gives you the added benefit of being G10N friendly.

Categories

Resources