Related
How to remove Consecutive Characters at each Iteration..
Below is the screenshot that explains the question with more details
MySolution
Initially I checked whether there are any Consecutive characters.
If yes,Then,remove all the consecutive characters and when there are no consecutive characters add the remaining characters to another String.
If no Consecutive Characters just simply increment it.
public static void print(){
String s1="aabcccdee"; I have taken a sample test case
String s2="";
for(int i=0;i<s1.length();){
if(s1.charAt(i)==s1.charAt(i+1)){
while(s1.charAt(i)==s1.charAt(i+1)){
i++;
}
for(int j=i+1;j<s1.length();j++){
s2=s2+s1.charAt(j);
}
s1=s2;
}
else
i++;
}
System.out.println(s1);
}
Output Shown
An infinite Loop
Expected Output for the give sample is
bd
Can Anyone guide me how to correct?
You can simply use String::replaceFirts with this regex (.)\1+ which means matche any charater (.) which followed by itself \1 one or more time + with empty.
In case you want to replace first by first you have to check the input, if after each iteration still contain more than one consecutive characters or not, in this case you can use Pattern and Matcher like this :
String[] strings = {"aabcccdee", "abbabba", "abbd "};
for (String str : strings) {
Pattern pattern = Pattern.compile("([a-z])\\1");
// While the input contain more than one consecutive char make a replace
while (pattern.matcher(str).find()) {
// Note : use replaceFirst instead of replaceAll
str = str.replaceFirst("(.)\\1+", "");
}
System.out.println(str);
}
Outputs
aabcccdee -> bd
abbabba -> a
abbd -> ad
Update
I had misread the question. The intent is to also remove the consecutive characters after each replacement. The below code does that.
private static String removeDoubles(String str) {
int s = -1;
for (int i = 1; i < str.length(); i++) {
// If the current character is the same as the previous one,
// remember its start position, but only if it is not set yet
// (its value is -1)
if (str.charAt(i) == str.charAt(i - 1)) {
if (s == -1) {
s = i - 1;
}
}
else if (s != -1) {
// If the current char is not equal to the previous one,
// we have found our end position. Cut the characters away
// from the string.
str = str.substring(0, s) + str.substring(i);
// Reset i. Notice that we don't have to loop from 0 on,
// instead we can start from our last replacement position.
i = s - 1;
// Finally reset our start position
s = -1;
}
}
if (s != -1) {
// Check the last portion
str = str.substring(0, s);
}
return str;
}
Note that this is almost 10 times faster than YCF_L's answer.
Original post
You are almost there, but you don't have to use multiple for loops. You just need one loop, because whether to remove characters from the string only depends on subsequent characters; we don't need to count anything.
Try this:
private static String removeDoubles(String s) {
boolean rem = false;
String n = "";
for (int i = 0; i < s.length() - 1; i++) {
// First, if the current char equals the next char, don't add the
// character to the new string and set 'rem' to true, which is used
// to remove the last character of the sequence of the same
// characters.
if (s.charAt(i) == s.charAt(i + 1)) {
rem = true;
}
// If this is the last character of a sequence of 'doubles', then
// reset 'rem' to false.
else if (rem) {
rem = false;
}
// Else add the current character to the new string
else {
n += s.charAt(i);
}
}
// We haven't checked the last character yet. Let's add it to the string
// if 'rem' is false.
if (!rem) {
n += s.charAt(s.length() - 1);
}
return n;
}
Note that this code is on average more than three times faster than regular expressions.
Try something like this:
public static void print() {
String s1 = "abcccbd"; // I have taken a sample test case
String s2 = "";
while (!s1.equals(s2)) {
s2 = s1;
s1 = s1.replaceAll("(.)\\1+", "");
}
System.out.println(s1);
}
consider this easier to understand code
String s1="aabcccdee";
while (true) {
rvpoint:
for (int x = 0; x < s1.length() -1; x++)
{
char c = s1.charAt(x);
if (c == s1.charAt(x+ 1)) {
s1 = s1.replace(String.valueOf(c), "");
continue rvpoint; // keep looping if a replacement was made
}
}
break; // break out of outer loop, if replacement not found
}
System.out.println(s1);
note
This will only work for the first iteration, put into a method and keep calling until the sizes do not change
For some reason when the string length is zero, it does not come out of the while loop. Can some one help me on this?
static String str1 = "";
public static void reverse(String str) {
while (str.length() > 0) {
str1 = str1 + str.charAt(str.length() - 1);
StringBuffer str_buf = new StringBuffer(str);
str = str_buf.deleteCharAt(str.length() - 1).toString();
reverse(str);
}
System.out.println("String is " + str1);
}
Replace while with if
if(str.length()>0)
Update:
The reason while fails is, after str.length() becomes 0, it hits the bottom of recursion, and control returns to the "higher" level, where str.length() is still 1. So it again calls itself.
So with while ,after it reaches 0, it will keep looping continuously between 1 and 0.
The way that you have it coded you are looping through the entire string and recursively calling the function. So for a short string "abcd" the first time through will call reverse with "abc", "ab", and "a". The reverse call to "abc" will call reverse with "ab" and "a". If you are recursively calling the function then you don't need the while loop as #sanjeev-mk suggested instead you just need the if as the exit condition.
I believe there is a more suitable code to recursively print string reverse:
public void reverseStringPrint(String inputString, int index){
if (index < (inputString.lenght() - 1))
reverseStringPrint(inputString, index + 1);
System.out.print(inputString.charAt(index);
}
Run with index = 0.
In order to get the reversed string at the output (not only print it) you may do it like this:
public String reverseString(String inputString, int index){
String restOfTheString = "";
if (index < (inputString.lenght() - 1))
restOfTheString = reverseStringPrint(inputString, index + 1);
return charAt(index) + restOfTheString;
}
I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.
String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?
Why not just String substr = word.substring(word.length() - 3)?
Update
Please make sure you check that the String is at least 3 characters long before calling substring():
if (word.length() == 3) {
return word;
} else if (word.length() > 3) {
return word.substring(word.length() - 3);
} else {
// whatever is appropriate in this case
throw new IllegalArgumentException("word has fewer than 3 characters!");
}
I would consider right method from StringUtils class from Apache Commons Lang:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)
It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.
Example usage:
StringUtils.right("abcdef", 3)
You can find more examples under the above link.
Here's some terse code that does the job using regex:
String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
This code returns up to 3; if there are less than 3 it just returns the string.
This is how to do it safely without regex in one line:
String last3 = str == null || str.length() < 3 ?
str : str.substring(str.length() - 3);
By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").
The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:
String last3;
if (str == null || str.length() < 3) {
last3 = str;
} else {
last3 = str.substring(str.length() - 3);
}
String newString = originalString.substring(originalString.length()-3);
public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}
If you want the String composed of the last three characters, you can use substring(int):
String new_word = word.substring(word.length() - 3);
If you actually want them as a character array, you should write
char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);
The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.
If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.
Here is a method I use to get the last xx of a string:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
Then use it like so:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
This method would be helpful :
String rightPart(String text,int length)
{
if (text.length()<length) return text;
String raw = "";
for (int i = 1; i <= length; i++) {
raw += text.toCharArray()[text.length()-i];
}
return new StringBuilder(raw).reverse().toString();
}
The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.
Try this link for a more verbose description of the getChars method.
I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.
You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);
Alternative way for "insufficient string length or null" save:
String numbers = defaultValue();
try{
numbers = word.substring(word.length() - 3);
} catch(Exception e) {
System.out.println("Insufficient String length");
}
This method will return the x amount of characters from the end.
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
//usage
System.out.println(lastXChars("stackoverflow", 4)); // flow
Java String trim is not removing a whitespace character for me.
String rank = (some method);
System.out.println("(" + rank + ")");
The output is (1 ). Notice the space to the right of the 1.
I have to remove the trailing space from the string rank but neither rank.trim() nor rank.replace(" ","") removes it.
The string rank just remains the same either way.
Edit: Full Code::
Document doc = Jsoup.connect("http://www.4icu.org/ca/").timeout(1000000).get();
Element table = doc.select("table").get(7);
Elements rows = table.select("tr");
for (Element row: rows) {
String rank = row.select("span").first().text().trim();
System.out.println("("+rank+")");
}
Why can't I remove that space?
The source code of that website shows the special html character . Try searching or replacing the following in your java String: \u00A0.
That's a non-breakable space. See: I have a string with "\u00a0", and I need to replace it with "" str_replace fails
rank = rank.replaceAll("\u00A0", "");
should work. Maybe add a double \\ instead of the \.
You should assign the result of trim back to the String variable. Otherwise it is not going to work, because strings in Java are immutable.
String orig = " quick brown fox ";
String trimmed = original.trim();
The character is a non-breaking space, and is thus not removed by the trim() method. Iterate through the characters and print the int value of each one, to know which character you must replace by an empty string to get what you want.
Are you assigning the String?
String rank = " blabla ";
rank = rank.trim();
Don't forget the second assignment, or your trimmed string will go nowhere.
You can look this sort of stuff up in the API as well: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#trim()
As you can see this method returns a String, like most methods that operate on a String do. They return the modified String and leave the original String in tact.
I had same problem and did little manipulation on java's trim() method.
You can use this code to trim:
public static String trimAdvanced(String value) {
Objects.requireNonNull(value);
int strLength = value.length();
int len = value.length();
int st = 0;
char[] val = value.toCharArray();
if (strLength == 0) {
return "";
}
while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) {
st++;
if (st == strLength) {
break;
}
}
while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) {
len--;
if (len == 0) {
break;
}
}
return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value;
}
Trim function returns a new copy of the string, with leading and trailing whitespace omitted.
rank = rank.trim();// This will remove and save rank without leading and trailing spaces
will give the result you want.
Replace method will not work if you pass empty string for replacement.
Since String in java are immutable ie they cannot be changed. You need to reassign it to some temporary string. And then using that string you can convert it into int.
String temp=rank.trim()
int te= Integer.parseInt(temp)
I am practicing over the summer to try and get better and I am a little stuck on the following:
http://www.javabat.com/prob/p123384
Given a string, return a new string where the first and last chars have been exchanged.
Examples:
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"
Code:
public String frontBack(String str)
{
String aString = "";
if (str.length() == 0){
return "";
}
char beginning = str.charAt(0);
char end = str.charAt(str.length() - 1);
str.replace(beginning, end);
str.replace(end, beginning);
return str;
}
Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the Java API and click on String in the lower left pane. That pane is sorted alphabetically.
Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say:
String temp = new String(charArray);
and return that. This is assuming that charArray is your array of chars.
Rather than using the String.replace method, I'd suggest using the String.substring method to get the characters excluding the first and last letter, then concatenating the beginning and end characters.
Furthermore, the String.replace method will replace all occurrences of the specified character, and returns a new String with the said replacements. Since the return is not picked up in the code above, the String.replace calls really don't do much here.
This is because String in Java is immutable, therefore, the replace method cannot make any changes to the original String, which is the str variable in this case.
Also to add, this approach won't work well with Strings that have a length of 1. Using the approach above, a call to String.substring with the source String having a length of 1 will cause a StringIndexOutOfBoundsException, so that will also have to be taken care of as a special case, if the above approach is taken.
Frankly, the approach presented in indyK1ng's answer, where the char[] is obtained from the String and performing a simple swap of the beginning and end characters, then making a String from the modified char[] is starting to sound much more pleasant.
String instances in Java are immutable. This means that you cannot change the characters in a String; a different sequence of characters requires a new object. So, when you use the replace method, throw away the original string, and use the result of the method instead.
For this method, however, you probably want to convert the String instance to an array of characters (char[]), which are mutable. After swapping the desired characters, create a new String instance with that array.
A couple of hints:
Strings are immutable, meaning they cannot be changed. Hence, str.replace() does not change str, instead it returns a new string.
Maybe replace isn't the best... Consider frontBack("abcabc"): your function, if it were corrected, would replace 'a' with 'c' yielding "cbccbc", then 'c' with 'a' yielding "abaaba". That's not quite right!
The replace method in String actually returns a String, so if you were to insist on using replace, you'd do:
beginReplace = str.replace( beginning, end );
endReplace = beginReplace.replace( end, beginning );
return( str );
But this actually doesn't solve your specific problem, because replace replaces all occurences of a character in the string with its replacement.
For example, if my string was "apple" and I said "apple".replace( 'p', 'q' ), the resulting string would be "aqqle."
Yet another example without creating additional objects:
if (str.length() > 1) {
char[] chars = str.toCharArray();
// replace with swap()
char first = chars[0];
chars[0] = chars[chars.length - 1];
chars[chars.length - 1] = first;
str = new String(chars);
}
return str;
Edit: Performing the swap on length = 1 string is no-op.
Edit 2: dfa's change to copyValueOf did not make any sense as the Java source says in String.java: "// All public String constructors now copy the data." and the call is just delegated to a string constructor.
You could use a regex..
return str.replaceFirst("(.)(.*)(.)", "$3$2$1");
Just another, slightly different, approach, so you get a sense of the spectrum of possibilities. I commend your attention to the quick exit for short strings (instead of nesting the more-complicated processing in an if() clause), and to the use of String.format(), because it's a handy technique to have in your toolbox, not because it's notably better than regular "+" concatenation in this particular example.
public static String exchange(String s) {
int n = s.length();
if (n < 2)
return s;
return String.format("%s%s%s", s.charAt(n - 1), s.substring(1, n - 1), s.charAt(0));
}
Simple solution is:
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
char[] cs = str.toCharArray();
char first = cs[0];
cs[0] = cs[cs.length -1];
cs[cs.length -1] = first;
return new String(cs);
}
Using a character array (watch out for the nasty empty String or null String argument!)
Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.
public String frontBack(String str) {
if (str == null || str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder(str);
char first = sb.charAt(0);
sb.setCharAt(0, sb.charAt(sb.length()-1));
sb.setCharAt(sb.length()-1, first);
return sb.toString();
}
Yet another approach (more for instruction than actual use) is this one:
public String frontBack(String str) {
if (str == null || str.length() < 2) {
return str;
}
StringBuilder sb = new StringBuilder(str);
String sub = sb.substring(1, sb.length() -1);
return sb.reverse().replace(1, sb.length() -1, sub).toString();
}
Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)
if (s.length < 2) {
return s;
}
return s.subString(s.length - 1) + s.subString(1, s.length - 2) + s.subString(0, 1);
(untested, indexes may be of by one...
public String frontBack(String input)
{
return
input.substring(input.length() - 1) + // The last character
input.substring(1, input.length() - 1) + // plus the middle part
input.substring(0, 1); // plus the first character.
}
You can use a StringBuilder that represents "a mutable sequence of characters".
It has all methods needed to solve the problem: charAt, setCharAt, length and toString.
public String lastChars(String a, String b) {
if(a.length()>=1&&b.length()>=1){
String str = a.substring(0,1);
String str1 =b.substring(b.length()-1);
return str+str1;
}
else if(a.length()==0&&b.length()==0){
String v ="#";
String z ="#";
return v+z;
}
else if(a.length()==0&&b.length()>=1){
String s ="#";
String s1 = b.substring(b.length()-1);
return s+s1;
}
else if(a.length()>=1&&b.length()==0){
String f= a.substring(0,1);
String h = "#";
return f+h;
}
return a;
}
You can use this code:
public String frontBack(String str) {
if (str.length() <= 1)
return str;
String mid = str.substring(1, str.length()-1);
// last + mid + first
return str.charAt(str.length()-1) + mid + str.charAt(0);
}
class swap
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("no of elements in array");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Elements");
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=a[i];
}
int end=n-1;
b[0]=b[end];
b[end]=a[0];
for(int i=0;i<n;i++)
{
System.out.println(b[i]);
}
}
}
if (str.length() <= 1) {
return str;
}
String mid = str.substring(1, str.length()-1);
return str.charAt(str.length()-1) + mid + str.charAt(0);
function frontBack(str: string) {
return str.slice(str.length - 1) + str.slice(1, -1) + str.slice(0, 1)
}
Slice will "cut out" the last letter. Counting the length of the string which is str.length -1, (plus) the reminder sliced string which starts at index 1 and is the last character which expressed at index -1, (plus) sliced last letter which is at index 0 through index 1.