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.
Related
I have string which goes like this-
abc/def/ghi/jkl/mno/pqr
Now I want to represent this as-
abc/
def/
ghi/
jkl/
mno/
pqr
I am trying to achieve this using JAVA, can any one please provide me a sample code.
Try with:
String input = "abc/def/ghi/jkl/mno/pqr";
String[] output = input.split("/");
for (int i = 0; i < output.length; i++) {
output[i] += "/";
}
One approach would be to replace each occurrence of "/" with "/\n" (\n is a new line character.)
String provides a replace() method for doing this.
I'll hint you. Have a look at the java docs for String class and find a method for replacing / with /\n in the string.
You can use the following code
String strValue="abc/def/ghi/jkl/mno/pqr";
String strValue1=strValue;
System.out.println("Actual Value \n >>>"+strValue);
strValue1=strValue1.replaceAll("/","/\n");
System.out.println("\nstrFormattedValue >>>\n"+strValue1);
The output of the program is as follows:-
Actual Value
>>>abc/def/ghi/jkl/mno/pqr
strFormattedValue >>>
abc/
def/
ghi/
jkl/
mno/
pqr
Press any key to continue . . .
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"
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);
I have an string str of unknown length (but not null) and a given maximum length len, this has to fit in. All I want to do, is to cut the string at len.
I know that I can use
str.substring(0, Math.min(len, str.length()));
but this does not come handy, if I try to write stacked code like this
code = str.replace(" ", "").left(len)
I know that I can write my own function but I would prefer an existing solution. Is there an existing left()-function in Java?
There's nothing built in, but Apache commons has the StringUtils class which has a suitable left function for you.
If you don't want to add the StringUtils Library you can still use it the way you want like so:
String string = (string.lastIndexOf(",") > -1 )?string.substring(0, string.lastIndexOf(",")): string;
Use Split.
String str = "Result string Delimiter Right String";
System.out.println(str.split("Delimiter")[0].trim());
Output: "Result string"
No there is not left() in the String class, as you can refer API. But as #Mark said Apache StringUtils has several methods: leftPad(), rightPad(), center() and repeat(). You can also check
this:http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringUtils.html
You can use String Format
In this example the format specifier "%-9s" means minimum 9 characters left justified (-).
"%-9.9s" means maximum 9 characters.
System.out.println (String.format("%-9.9s","1234"));
System.out.println (String.format("%-9.9s","123456789ABCD"));
int len=9;
System.out.println (String.format("%-"+len+"."+len+"s","123456789ABCD"));
Prints:
1234
123456789
123456789
in OP's case it would be something like this:
static final int MAXLEN=9;
code = String.format("%-"+MAXLEN+"."+MAXLEN+"s",str.replace(" ", ""));
put the below function in a class:
public static String getLeftString(String st,int length){
int stringlength=st.length();
if(stringlength<=length){
return st;
}
return st.substring((stringlength-length));
}
in my case I want to get date only.
String s = "date:2021-01-01";
int n = s.length() - 10; //10 was the length of the date
String result = s.substring(n);
the result will be "2021-01-01";
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.