I have a string in the format: /constant/variableurl . What is the best way out, such that, I can get the variableurl alone as a string.
I understand string tokenizer and regex are the two way out, but not sure how to split the last variableurl alone.
Any help is appreciated.
According to your explanation and example this is code that you could use (not perfect, generic)
toFind.substring(toFind.lastIndexOf("/") + 1)
where
String toFind = "/constant/variableurl"
There are many ways to achieve that:
String[] res = myStr.split("\\/");
String myStr = res[res.length - 1];
myStr = myStr.substring(myStr.lastIndexOf('/') + 1);
...
To add more methods, visit the docs.
If the constant portion of the string is the same for all your strings, you can get the variable portion of it using substring, and passing the length of the common part:
String a = "/constant/hello/world";
String b = "/constant/quick/brown/fox";
String c = "/constant/jumps/over/the/lazy/dog";
int len = "/constant/".length(); // That's 10
a = a.substring(len); // Becomes "hello/world"
b = a.substring(len); // Becomes "quick/brown/fox"
c = a.substring(len); // Becomes "jumps/over/the/lazy/dog"
Related
I'm wondering about how to replace generic characters in a Java string:
String original = "alt width = (SOME NUMBERS)"
and I want to make it like
String edited = "alt width = 640"
I haven't found out anything about on the web.
To be generic enough to replace any integer number:
int number; // this can be any integer
String original = String.format("alt width = %d",number);
Or if the numbers are represented as a String e.g "111,121"
String numbers;
String original = String.format("alt width = %s",numbers);
The replace method should do the trick:
String edited = original.replace("(SOME NUMBERS)", "640");
EDIT:
Based on the clarification in the comments, you could just remove the last three characters and replace them with what you need:
String edited = original.substring(0, original.length() - 3) + "640";
The most obvious answer is String.replace option. but you already got that answer.
A more generic option is using regular expressions:
String original = "alt width = 123";
int someNumbers = 640;
String edited=original.replaceFirst("[0-9]+",Integer.toString(someNumbers));
System.out.println(edited);
This will replace any numbers on the string. So the input string can be different but you'll get the same results:
String original = "alt width = 123 cm";
String original = "alt width = 123; alt height = 456"; //only 123 will be replaced 456 will be left as is.
You can modify the regex to fit other criteria.
I will prepare String for use substring function and i need to have always 4 characters. In stackoverflow I found code like this but it is works only for numbers.
writeHead = String.format("%04d", writeHead);
But in my case i need to do this same for text + numbers.
12a --> 012a
String head = "12a";
String writeHead = String.format("%04d", head);//doesnt work
//need 012a as String
String.format is not good if yor text/number pattern is fixed (i.e. all your numbers ends with letter a?).
A quick and dirty left padding with zeroes:
String head="12a";
String writeHead = "0000"+head;
writeHead=writeHead.substring(writeHead.length()-4);
a simple thing like this will do
String head = "12a";
while(head.length < 4){
head += "0"+head;
}
just check the length and append
int head = 12;
String writeheader = String.format("0%da", head);
or
String header = 12a;
String writeHeader = String.format("0%s", head);
I was just wondering if there was a way to replace strings with variables. Specifically through the methods replaceAll("", ""). Wondering if its possible to do something like :
int i = 2;
replaceAll("\\D", i);
If not, is there a roundabout way to do this?
You can only replace parts of Strings with a String.
String text = "Hello World";
int i = 2;
text = text.replaceAll("o", ""+i);
String#replaceAll(x,x) only accepts a String as its second parameter. The solution here is to convert your int into a String:
myString.replaceAll("\\D", String.valueOf(i));
use this:
int i = 2;
replaceAll("\\D", ""+i);
yes it is. As you assume you can use
s = s.replaceAll("textToReplace",Integer.toString(i));
to replace all the occurrences of textToReplace in the String s.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to upper case every first letter of word in a string?
Most efficient way to make the first character of a String lower case?
I want to convert the first letter of a string to upper case. I am attempting to use replaceFirst() as described in JavaDocs, but I have no idea what is meant by regular expression.
Here is the code I have tried so far:
public static String cap1stChar(String userIdea)
{
String betterIdea, userIdeaUC;
char char1;
userIdeaUC = userIdea.toUpperCase();
char1 = userIdeaUC.charAt(0);
betterIdea = userIdea.replaceFirst(char1);
return betterIdea;
}//end cap1stChar
The compiler error is that the argument lists differ in lengths. I presume that is because the regex is missing, however I don't know what that is exactly.
Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.
What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.
What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:
char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);
Or, if you feel comfortable with more complex, one-lined java code:
betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);
Both of these do the same thing, which is converting the first character of userIdea to an upper case character.
Or you can do
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
public static String cap1stChar(String userIdea)
{
char[] stringArray = userIdea.toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
return userIdea = new String(stringArray);
}
Comilation error is due arguments are not properly provided, replaceFirst accepts regx as initial arg. [a-z]{1} will match string of simple alpha characters of length 1.
Try this.
betterIdea = userIdea.replaceFirst("[a-z]{1}", userIdea.substring(0,1).toUpperCase())
String toCamelCase(String string) {
StringBuffer sb = new StringBuffer(string);
sb.replace(0, 1, string.substring(0, 1).toUpperCase());
return sb.toString();
}
userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
I am trying to concatenate and trying to parse at the same time. I am right now making a excel like program where I can say a1 = "Hello" + "World" and in the cell of A1 have it say HelloWorld. I just need to know how to parse the adding sign and connect those two words. Please tell me if you need more code to understand this, like the runner.
This is my parseInput class :
public class ParseInput {
private static String inputs;
static int col;
private static int row;
private static String operation;
private static Value field;
public static void parseInput(String input){
//splits the input at each regular expression match. \w is used for letters and \d && \D for integers
inputs = input;
Scanner tokens = new Scanner(inputs);
String none0 = tokens.next();
#SuppressWarnings("unused")
String none1 = tokens.next();
operation = tokens.nextLine().substring(1);
String[] holder = new String[2];
String regex = "(?<=[\\w&&\\D])(?=\\d)";
holder = none0.split(regex);
row = Integer.parseInt(holder[1]);
col = 0;
int counter = -1;
char temp = holder[0].charAt(0);
char check = 'a';
while(check <= temp){
if(check == temp){
col = counter +1;
}
counter++;
check = (char) (check + 1);
}
System.out.println(col);
System.out.println(row);
System.out.println(operation);
setField(Value.parseValue(operation));
Spreadsheet.changeCell(row, col, field);
}
public static Value getField() {
return field;
}
public static void setField(Value field) {
ParseInput.field = field;
}
}
This is actually a pretty complicated problem unless you can constrain input to a very small subset of what Excel accepts. If not then you'll probably want to look into something like ANTLR. However, assuming the above input then you'll want to do something like:
Split the string on the equal sign into s1 and s2
Split s2 on the plus sign into s3 and s4.
Trim all the strings, remove the quotes around s3 and s4.
Concatenate s3 and s4 and assign to your datastore indexed by s1.
Depending on how complex your concatenation needs are you can either use string concatenation or a StringBuilder:
result = "" + s3 + s4; // string concatenation
result = new StringBuilder().append(s3).append(s4).toString(); // StringBuilder
Let me know if you have any questions about any of the steps detailed above.
Details on (1) above, assuming input is a1 = "Hello" + "World":
String[] strings = input.split("=");
String s1 = strings[0].trim(); // a1
String s2 = strings[1].trim(); // "Hello" + "World"
strings = s2.split("+");
String s3 = strings[0].trim().replaceAll("^\"", "").replaceAll("\"$", "") // Hello
String s4 = strings[1].trim().replaceAll("^\"", "").replaceAll("\"$", ""); // World
String field = s3 + s4;
String colString = s1.replaceAll("[\\d]", ""); // a
String rowString = s1.replaceAll("[\\D]", ""); // 1
int col = colString.charAt(0) - 'a'; // 0
int row = Integer.parseInt(rowString);
Spreadsheet.changeCell(row, col, field);
I suggest you to implement your custom grammar using a parser generator like JavaCC.
Here you can find a simple tutorial.
I believe this is the better solution because in this way you can handle every expression you need.
Are you sure you want to use all the classes you are using? To parse something like "a=b+c+d.." (assuming you are not trying to validate), easiest and possibly the most efficient way is to use split API in Java lang String
Then join whatever is required using StringBuilder
You need to design and implement a parser and an evaluator. And before that, you need to design the language that your parser/evaluator is going to evaluate.
How to do it.
If your language is really simple, you can get away with parsing it by hand, using something like StringTokenizer to do the tokenization,
Otherwise, you are probably best off learning to use a Java "parser generator" such as JavaCC or ANTLR.
Either way, you need to do some background reading to understand all of the terminology. You could start with Wikipedia and/or the tutorial material from one of the parser generators. Alternatively, there are good textbooks on this topic.
In addition to what Abdullah said, if you really want to save every single ounce of memory you can, you should use the StringBuilder instead of the String concatenation. I believe i read somewhere before that the String concatenation make a new string object for each concatenations while the StringBuilder will add them all to a single String. Shouldn't matter too much though.
In my early life I made an equation evaluator in your style. It cost me huge code and complexity, because of my unawareness about Expression trees. But now with this you will be able to add more capabilities to your parser easily and with native JAVA codes. You will get tons of example of using Expression Trees.