Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

Saturday, 18 June 2016

Swap two String variables in java without using a third variable.

First way to do it as below,

String s1 = "First";
String s2 = "Second";
    s1=s1+" "+s2;
s2=s1.split(" ")[0];
s1=s1.split(" ")[1];
System.out.println(s1 + " " + s2);


Another way to do it as,

String a="First";
String b="Second";

    a= a+b;
    b = a.substring(0,(a.length()-b.length())); 
    a = a.substring(b.length());

    System.out.println("a = "+a);
    System.out.println("b = "+b); 

one more way to do this as below,

String returnFirstString(String x, String y) {
    return x;
}

String a = "First"
String b = "Second"
a = returnFirstString(b, b = a); 
System.out.print(a+" "+b);


Another one more way we can do its as,

String s1 = "First";
String s2 = "Second";
AtomicReference<String> String1 = new AtomicReference<String>(s1);
AtomicReference<String> String2 = new AtomicReference<String>(s2);
String1.set(String2.getAndSet(String1.get()));
System.out.println(String1 + " " + String2);

Java Strings are implemented with references, so you need to swap their references.

Remove special characters(?) from String.

\p{ASCII} is POSIX character classes.It will replace the non ascii string and return the string(Printable ASCII).



String string=givenString.replaceAll("[^\\p{ASCII}]", "");

Thursday, 16 June 2016

Write a method to reverse a String in java.

In Java, a String is immutable, so once it has been constructed it is not possible to change the contents. So when you are asked to reverse a String, you are actually being asked to produce a new String object, with the contents reversed,


public static String reverse(final String s)

Approach to reversing a String is to iterate over the contents in reverse

public static String reverse(final String s) {
final StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}

Or we can do by using Built-in Re verse Methods

Note-This approach, is fine when we do it with small size of data,  It hold the original String and the StringBuilder in memory and occupy large memory. This could be problematic if you were reversing some data of several gigabytes in size.



public static String stringReverse(final String s) {
final StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() / 2; i++) {
final char tmp = sb.charAt(i);
final int otherEnd = sb.length() - i - 1;
sb.setCharAt(i, sb.charAt(otherEnd));
sb.setCharAt(otherEnd, tmp);
}
return sb.toString();
}

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...