This is an interview question. I was thinking of a solution in java. This questions seems very simple, is there a catch here?
I was thinking of the following solution:
string1 + 1*hash(String1) + string2 + 2*hash(String2).
If I concat strings like this, then I can decode them as well easily into 2 separate strings.
Am I missing something in the question?
Encode:
String encoded = new JsonArray().add(str1).add(str2).toString();
Decode:
JsonArray arr = JsonArray.readFrom(encoded);
String str1 = arr.get(0).asString();
String str2 = arr.get(1).asString();
Here I use minimal-json lib, but it's pretty similar with any other JSON library as well.
Note that it's usually a bad idea to invent new formats of encoding the information into the string as you have plenty of existing ones (xml, json, yaml, etc.) which already solved all the possible issues like symbol escaping and exception handling.
To encode:
String encoded = ""+str1.length()+"/"+str1+str2;
To decode:
String[] temp = encoded.split("/", 2);
int length1 = Integer.parseInt(temp[0]);
String str1 = temp[1].substring(0, length1);
String str2 = temp[1].substring(length1);
Explanation:
The encoded string is in the form "<number>/<str1><str2>". When you call split(regex, limit) the size of the resulting array will be at most limit, considering only the first matches of regex. Thus even if your strings contain the character / you can be sure that the resulting array will be {"<number>", "<str1><str2>"}.
the substring(begin, end) return a string starting at begin inclusive and ending at end exclusive, giving you a resulting substring of end-begin length. Since you are calling it with values(0, str1.length()) what you get is exactly str1. The last call will return a substring from str1.length(), which is also the index of the first character of str2, to the end of the string (which is the end of str2).
Reference: String javadoc page
One way is to use the length of the first string.
// encode
String concat = string1 + string2;
// decode
String str1 = concat.substring( 0, string1.length() );
String str2 = concat.substring( string1.length(), concat.length() );
Another way is to use a delimiter. But the delimiter character should not be included in any of the strings to be joined.
// encode
String concat = "hello" + "`" + "world!";
// decode
String[] decoded = concat.split("`");
String str1 = decoded[0];
String str2 = decoded[1];
Related
I am trying to replace only one character of a string. But whenever the character has multiple occurrences within the string, all of those characters are being replaced, while I only want the particular character to be replaced. For example:
String str = "hello world";
str = str.replace(str.charAt(2), Character.toUpperCase(str.charAt(2)));
System.out.println(str);
Gives the result:
heLLo worLd
while I want it to be:
heLlo world
What can I do to achieve this?
replace will not work because it replace all the occurrence in the string. Also replaceFirst will not work as it will always remove
the first occurrence.
As Strings are non mutable , so in either way you need create a new string always. Can be done by either of the following.
Use substring, and manually create the string that you want.
int place = 2;
str = str.substring(0,place)+Character.toUpperCase(str.charAt(place))+str.substring(place+1);
Convert the string to array of characters and replace any character that you want by using index, and then convert array back to the string.
You should use a StringBuilder instead of String to achieve this goal.
This code works too
String str = "hello world";
str = str.replaceFirst(String.valueOf(str.charAt(2)),
String.valueOf(Character.toUpperCase(str.charAt(2))));
System.out.println(str);
String str = "hello world";
char[] charArray = str.toCharArray();
charArray[2] = Character.toUpperCase(charArray[2]);
str = new String(charArray);
System.out.println(str);
replace(char, char) will replace all occurrences of the specified char, not only the char at the index. From the documentation
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
You can do something like
String str = "hello world";
String newStr = str.substring(0, 2) + Character.toUpperCase(str.charAt(2)) + str.substring(3);
I'm retrieving Strings from the database and storing in into a String variable which is inside the for loop. Few Strings i'm retrieving are in the form of:
https://www.ppltalent.com/test/en/soln-computers-ltd
and few are in the form of
https://www.ppltalent.com/test/ja/aman-computers-ltd
I want split string into two substrings i.e
https://www.ppltalent.com/test/en/soln-computers-ltd as https://www.ppltalent.com/test/en and /soln-computers-ltd.
It can easily be separated if i would have only /en.
String[] parts = stringPart.split("/en");
System.out.println("Divided String : "+ parts[1]);
But in many of the strings it has /jr , /ch etc.
So how can I split them in two sub-strings?
You could perhaps use the fact that /en and /ja are both preceeded by /test/. So, something like indexOf("/test/") and then substring.
In your examples, it seems like you're interested in the very last part, which could be retrieved by lastIndexOf('/') for instance.
Or, using look-arounds you could do
String s1 = "https://www.ppltalent.com/test/en/soln-computers-ltd";
String[] parts = s1.split("(?<=/test/../)");
System.out.println(parts[0]); // https://www.ppltalent.com/test/er/
System.out.println(parts[1]); // soln-computers-ltd
Split on the last /
String fullUrl = "https:////www.ppltalent.com//test//en//soln-computers-ltd";
String baseUrl = fullUrl.substring(0, fullUrl.lastIndexOf("//"));
String manufacturer = fullUrl.subString(fullUrl.lastIndexOf("//"));
I have the String content://com.android.contact/data/5032 in a variable Str1. I want to manipulate Str1 so that I will get 5032 in another string variable.
Can anyone suggest the answer?
String str1 = "content://com.android.contact/data/5032"
String val = str1.substring(str1.lastIndexOf("//")+1);
If you want go get digits from the given string try this:
String str = "content://com.android.contact/data/5032";
String str2 = str.replaceAll("\\D+","");
System.out.println(str2);
Output:
5032
If you want to split try this:
String[] string = str.split("//|/");
System.out.println(string[string.length -1 ]);
Output:
5032
String str1 = "content://com.android.contact/data/5032";
String str2 = str1.substring(str1.lastIndexOf("/")+1, str1.length());
if you only want the last 4 chars, you can do something like this
String s = "this is a string";
String ss = s.substring(s.length()-4, s.length());
but if you need to extract the number from random positions, you will have to use regular expressions.
Please write names of variables starting with a small letter. You can use the split method to do this. You might find this related question interesting: How to split a string in Java.
I'm trying to split some user input. The input is of the form a1 b2 c3 d4.
For each input (eg; a1), how do I split it into 'a' and '1'?
I'm familiar with the string split function, but what do I specify as the delimiter or is this even possible?
Thanks.
You could use String#substring()
String a1 = "a1"
String firstLetterStr = a1.substring(0,1);
String secondLetterStr = a1.substirng(1,a1.length());
Similarly,
String c31 = "c31"
String firstLetterStr = c31.substring(0,1);
String secondLetterStr = c31.substirng(1,c31.length());
If you want to split the string generically (rather than trying to count characters per the other answers), you can still use String.split(), but you have to utilize regular expressions. (Note: This answer will work when you have strings like a1, a2, aaa333, etc.)
String ALPHA = "\p{Alpha}";
String NUMERIC = "\d";
String test1 = "a1";
String test2 = "aa22";
ArrayList<String> alpha = new ArrayList();
ArrayList<String> numeric = new ArrayList();
alpha.add(test1.split(ALPHA));
numeric.add(test1.split(NUMERIC));
alpha.add(test2.split(ALPHA));
numeric.add(test2.split(NUMERIC));
At this point, the alpha array will have the alpha parts of your strings and the numeric array will have the numeric parts. (Note: I didn't actually compile this to test that it would work, but it should give you the basic idea.)
it really depends how you're going to use the data afterwards, but besides split("") or accessing individual characters by index, one other way to split into individual character is toCharArray() -- which just breaks the string into an array of characters...
Yes, it is possible, you can use split("");
After you split user input into individual tokens using split(" "), you can split each token into characters using split("") (using the empty string as the delimiter).
Split on space into an array of Strings, then pull the individual characters with String.charAt(0) and String.charAt(1)
I would recommend just iterating over the characters in threes.
for(int i = 0; i < str.length(); i += 3) {
char theLetter = str.charAt(i);
char theNumber = str.charAt(i + 1);
// Do something
}
Edit: if it can be more than one letter or digit, use regular expressions:
([a-z]+)(\d+)
Information: http://www.regular-expressions.info/java.html
In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}