Extract digits from a string in Java - java

I have a Java String object. I need to extract only digits from it. I'll give an example:
"123-456-789" I want "123456789"
Is there a library function that extracts only digits?
Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?

You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");

Here's a more verbose solution. Less elegant, but probably faster:
public static String stripNonDigits(
final CharSequence input /* inspired by seh's comment */){
final StringBuilder sb = new StringBuilder(
input.length() /* also inspired by seh's comment */);
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
if(c > 47 && c < 58){
sb.append(c);
}
}
return sb.toString();
}
Test Code:
public static void main(final String[] args){
final String input = "0-123-abc-456-xyz-789";
final String result = stripNonDigits(input);
System.out.println(result);
}
Output:
0123456789
BTW: I did not use Character.isDigit(ch) because it accepts many other chars except 0 - 9.

public String extractDigits(String src) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}

Using Google Guava:
CharMatcher.inRange('0','9').retainFrom("123-456-789")
UPDATE:
Using Precomputed CharMatcher can further improve performance
CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();
ASCII_DIGITS.retainFrom("123-456-789");

input.replaceAll("[^0-9?!\\.]","")
This will ignore the decimal points.
eg: if you have an input as 445.3kg the output will be 445.3.

Using Google Guava:
CharMatcher.DIGIT.retainFrom("123-456-789");
CharMatcher is plug-able and quite interesting to use, for instance you can do the following:
String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);
output == 123-456-789

public class FindDigitFromString
{
public static void main(String[] args)
{
String s=" Hi How Are You 11 ";
String s1=s.replaceAll("[^0-9]+", "");
//*replacing all the value of string except digit by using "[^0-9]+" regex.*
System.out.println(s1);
}
}
Output: 11

Use regular expression to match your requirement.
String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();
System.out.print(num);
}

I inspired by code Sean Patrick Floyd and little rewrite it for maximum performance i get.
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
while ( buffer.hasRemaining() ) {
char chr = buffer.get();
if ( chr > 47 && chr < 58 )
result[cursor++] = chr;
}
return new String( result, 0, cursor );
}
i do Performance test to very long String with minimal numbers and result is:
Original code is 25,5% slower
Guava approach is 2.5-3 times slower
Regular expression with D+ is 3-3.5 times slower
Regular expression with only D is 25+ times slower
Btw it depends on how long that string is. With string that contains only 6 number is guava 50% slower and regexp 1 times slower

Using Kotlin and Lambda expressions you can do it like this:
val digitStr = str.filter { it.isDigit() }

You can use str.replaceAll("[^0-9]", "");

I have finalized the code for phone numbers +9 (987) 124124.
Unicode characters occupy 4 bytes.
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
int i=0;
while ( i< buffer.length() ) { //buffer.hasRemaining()
char chr = buffer.get(i);
if (chr=='u'){
i=i+5;
chr=buffer.get(i);
}
if ( chr > 39 && chr < 58 )
result[cursor++] = chr;
i=i+1;
}
return new String( result, 0, cursor );
}

Code:
public class saasa {
public static void main(String[] args) {
// TODO Auto-generated method stub
String t="123-456-789";
t=t.replaceAll("-", "");
System.out.println(t);
}

import java.util.*;
public class FindDigits{
public static void main(String []args){
FindDigits h=new FindDigits();
h.checkStringIsNumerical();
}
void checkStringIsNumerical(){
String h="hello 123 for the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
if(h.charAt(i)!=' '){
System.out.println("Is this '"+h.charAt(i)+"' is a digit?:"+Character.isDigit(h.charAt(i)));
}
}
}
void checkStringIsNumerical2(){
String h="hello 123 for 2the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
char chr=h.charAt(i);
if(chr!=' '){
if(Character.isDigit(chr)){
System.out.print(chr) ;
}
}
}
}
}

Related

How to convert given string in comma seperated characters in java?

public class StringDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name = "String";
char[] c = name.toCharArray();
for (char ch : c) {
System.out.print(ch);
System.out.print(",");
}
}
}
This gives me output as
S,t,r,i,n,g,
I don't want that last comma, how to get output as S,t,r,i,n,g
You can also do it on a higher level without writing your own loop. It's not faster or anything, but the code is more clear about what it's doing: "Split my string into characters and join it back together, separated by commas!" ...
String name = "String";
String separated = String.join(",", name.split(""));
System.out.println(separated);
EDIT: String.join() is available from Java 1.8 and up.
I would personally use a StringBuilder for this task.
What you need, is to apply some logic that can distinguish whether or not a comma is needed. You loop through the characters just like you did and you always append a comma before the next character, except on the first iteration.
Example:
public static void main(String[] args) {
String test = "String";
StringBuilder sb = new StringBuilder();
for (char ch : test.toCharArray()) {
if (sb.length() != 0) {
sb.append(",");
}
sb.append(ch);
}
System.out.println(sb.toString());
}
Output:
S,t,r,i,n,g
Another way without StringBuilder and using just a traditional for loop, but using the same logic:
public static void main(String[] args) {
String test = "String";
char[] chars = test.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i != 0) {
System.out.print(",");
}
System.out.print(chars[i]);
}
}
Output:
S,t,r,i,n,g
Sure, but for this you need a for loop based on the length of c, other solutions are not as straight IMHO:
String name="String";
char[] c = name.toCharArray();
for (int i = 0; i < c.length; i++){
char ch = c[i];
System.out.print(ch);
if( i != c.length -1 ){
System.out.print(",");
}
}
Some additional 2 Cents:
You can stream the character int values, map them to a List<String> where each element is a single char as String and finally use String.join(..., ...) in order to get the desired result, a comma separated String of all the characters in the original String:
public static void main(String[] args) {
// take an example String
String name = "Stringchars";
// make a list of characters as String of it by streaming the chars
List<String> nameCharsAsString = name.chars()
// mapping each one to a String
.mapToObj(e -> String.valueOf((char) e))
// and collect them in a list
.collect(Collectors.toList());
// then join the elements of that list to a comma separated String
String nameCharsCommaSeparated = String.join(",", nameCharsAsString);
// and print it
System.out.println(nameCharsCommaSeparated);
}
Running this code results in the following output:
S,t,r,i,n,g,c,h,a,r,s
This is just another possibility of getting your desired result, it is not necessarily the best solution.
You can use Stream to do that. Please check below,
String result = Arrays.stream(name.split("")).collect(Collectors.joining(","));
Output:
S,t,r,i,n,g

How to split a string after 2nd occurrence of dot(.) in java

I have a string which looks something like this(the most basic form):
String str = "1.0.0.190"
The str can be something like this as well:
1.11.0.12 or 2.111.1.190 or 1.0.0.0
I want to split the string at the 2nd occurrence of the dot(.). How can I achieve that ?
Output:
String str = "1.0.0.190"
String output = "1.0"
I'd fit the answer to OP's level, so I wouldn't recommend split or regexps to him...
If you need substring to second dot, simply find second dot and cut the string to that position...
public class DotSubstring {
public static void main(String[] args) {
String s = "1.2.3.4";
int secondDotPosition = findSecondDotPosition(s);
if (secondDotPosition > 0) {
System.out.println(s.substring(0, secondDotPosition));
} else {
System.out.printf("ERROR: there is not a 2nd dot in '%s'%n", s);
}
}
private static int findSecondDotPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == '.') --dotsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
}
The problem with split for beginner is, that is accepts regexp, that's why it is escaped in Joop Eggen's answe like this str.split("\\.").
And yes, that can be achieved in one line as user3458271 wrote in a comment same as xyz later in answer, just error checking would be more difficult (for example if there are no 2 dots...).
In one line with substring and indexOf:
String output = str.substring(0,str.indexOf(".",str.indexOf(".")+1));
public static void main(String[] args) {
String input = "2.111.1.190";
String[] out = input.split("\\.");
String output1 = out[0]+"."+out[1];
System.out.println(output1);
String output2 = "";
for(int x=2; x < out.length; x++)
output2 += out[x] +".";
System.out.println(output2);
}
For the other fields too:
String[] halfs = str.split("\\.");
String[] fulls = new String[halfs.length / 2];
for (int i = 0; i < fulls.length; ++i) {
fulls[i] = halfs[2*i] + "." + halfs[2*i + 1];
}
return fulls[0];
The same technique reduced for the first field:
String[] halfs = str.split("\\.", 3);
return halfs[0] + "." + halfs[1];
Simply:
return str.replaceAll("^([^.]*\\.[^.]*)\\..*$", "$1");

Write a method to replace all spaces in a string with '%20'?

I have a question about a programming problem from the book Cracking The Code Interview by Gayl Laakmann McDowell, 5th Edition.
I'm not sure what is wrong with my answer? It varies a lot from the answer given in the book.
public String replace(String str){
String[] words = str.split(" ");
StringBuffer sentence = new StringBuffer();
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
return sentence.toString();
}
Question in the book says:
Note: if implementing in Java, please use a character array so that
you can perform this operation in place.
It also says that the char array that you get as input is long enough to hold the modified string.
By using split and StringBuffer you use additional O(n) space. That's why your answer varies a lot and is incorrect (apart from adding additional "%20").
In this loop, the program adds %20 before each word:
for(String w: words){
sentence.append("%20");
sentence.append(w);
}
That will produce incorrect results, for example for a b it will give %20a%20b.
There's a much simpler solution:
public String replace(String str) {
return str.replaceAll(" ", "%20");
}
Or, if you really don't want to use .replaceAll, then write like this:
public String replace(String str) {
String[] words = str.split(" ");
StringBuilder sentence = new StringBuilder(words[0]);
for (int i = 1; i < words.length; ++i) {
sentence.append("%20");
sentence.append(words[i]);
}
return sentence.toString();
}
You can also do the following, which replaces any space
String s = "Hello this is a string!";
System.out.println(replaceSpace(s, "%20"));
public static String replaceSpace(String s, String replacement) {
String ret = s.replaceAll(" *", replacement);
return ret;
}
Gives
Hello%20this%20is%20a%20string!
One of the simplest way:
public void replaceAll( String str )
{
String temp = str.trim();
char[] arr = temp.toCharArray();
StringBuffer sb = new StringBuffer();
for( int i = 0; i < arr.length; i++ )
{
if( arr[i] == ' ' )
{
sb.append( "%20" );
}
else
{
sb.append( arr[i] );
}
}
}
private static String applyReplaceOperationWithCount(String str) {
if (StringUtils.isEmpty(str)) { //if string is null or empty, return it
return str;
}
char[] strChar = str.toCharArray();
int count = 0; //count spaces in the string to recalculate the array length
for (char c : strChar) {
if (c == ' ') {
count++;
}
}
if (count == 0) { // if there are no spaces in the string, return it
return str;
}
int length = strChar.length;
char[] newChar = new char[length + (count * 2)]; // 1 char will be replaced by 3 chars. So the new length should be count*2 larger than original
int index = 0;
for (char c : strChar) {
if (c != ' ') { // if char is not a space just push it in the next available location
newChar[index++] = c;
} else { // if char is a space just push %,2,0
newChar[index++] = '%';
newChar[index++] = '2';
newChar[index++] = '0';
}
}
return new String(newChar); // convert the new array into string
}
I am using matches and replaceAll it works well.
public class ReplaceSpaces {
public static void main(String[] args) {
String text = " Abcd olmp thv ";
if(text.matches(".*\\s+.*")){
System.out.println("Yes I see white space and I am replacing it");
String newText = text.replaceAll("\\s+", "%20");
System.out.println(newText);
}
else{
System.out.println("Nope I dont see white spaces");
}
}
}
Output
Yes I see white space and I am replacing it
%20Abcd%20olmp%20thv%20
public static String replaceSpaceInString(String string,String toreplace){
String replacedString = "";
if(string.isEmpty()) return string;
string = string.trim();
if(string.indexOf(" ") == -1)return string;
else{
replacedString = string.replaceAll("\\s+",toreplace);
}
return replacedString;
}

Removing duplicates from a String in Java

I am trying to iterate through a string in order to remove the duplicates characters.
For example the String aabbccdef should become abcdef
and the String abcdabcd should become abcd
Here is what I have so far:
public class test {
public static void main(String[] args) {
String input = new String("abbc");
String output = new String();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < output.length(); j++) {
if (input.charAt(i) != output.charAt(j)) {
output = output + input.charAt(i);
}
}
}
System.out.println(output);
}
}
What is the best way to do this?
Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
System.out.println(sb.toString());
Using Stream makes it easy.
noDuplicates = Arrays.asList(myString.split(""))
.stream()
.distinct()
.collect(Collectors.joining());
Here is some more documentation about Stream and all you can do with
it :
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
The 'description' part is very instructive about the benefits of Streams.
Try this simple solution:
public String removeDuplicates(String input){
String result = "";
for (int i = 0; i < input.length(); i++) {
if(!result.contains(String.valueOf(input.charAt(i)))) {
result += String.valueOf(input.charAt(i));
}
}
return result;
}
I would use the help of LinkedHashSet. Removes dups (as we are using a Set, maintains the order as we are using linked list impl). This is kind of a dirty solution. there might be even a better way.
String s="aabbccdef";
Set<Character> set=new LinkedHashSet<Character>();
for(char c:s.toCharArray())
{
set.add(Character.valueOf(c));
}
Create a StringWriter. Run through the original string using charAt(i) in a for loop. Maintain a variable of char type keeping the last charAt value. If you iterate and the charAt value equals what is stored in that variable, don't add to the StringWriter. Finally, use the StringWriter.toString() method and get a string, and do what you need with it.
Here is an improvement to the answer by Dave.
It uses HashSet instead of the slightly more costly LinkedHashSet, and reuses the chars buffer for the result, eliminating the need for a StringBuilder.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
Set<Character> present = new HashSet<>();
int len = 0;
for (char c : chars)
if (present.add(c))
chars[len++] = c;
System.out.println(new String(chars, 0, len)); // abcdeftz
Java 8 has a new String.chars() method which returns a stream of characters in the String. You can use stream operations to filter out the duplicate characters like so:
String out = in.chars()
.mapToObj(c -> Character.valueOf((char) c)) // bit messy as chars() returns an IntStream, not a CharStream (which doesn't exist)
.distinct()
.map(Object::toString)
.collect(Collectors.joining(""));
String input = "AAAB";
String output = "";
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index % input.length()) != input
.charAt((index + 1) % input.length())) {
output += input.charAt(index);
}
}
System.out.println(output);
but you cant use it if the input has the same elements, or if its empty!
Code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra array is not:
import java.util.*;
public class Main{
public static char[] removeDupes(char[] arr){
if (arr == null || arr.length < 2)
return arr;
int len = arr.length;
int tail = 1;
for(int x = 1; x < len; x++){
int y;
for(y = 0; y < tail; y++){
if (arr[x] == arr[y]) break;
}
if (y == tail){
arr[tail] = arr[x];
tail++;
}
}
return Arrays.copyOfRange(arr, 0, tail);
}
public static char[] bigArr(int len){
char[] arr = new char[len];
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()-=_+[]{}|;:',.<>/?`~";
for(int x = 0; x < len; x++){
arr[x] = alphabet.charAt(r.nextInt(alphabet.length()));
}
return arr;
}
public static void main(String args[]){
String result = new String(removeDupes(new char[]{'a', 'b', 'c', 'd', 'a'}));
assert "abcd".equals(result) : "abcda should return abcd but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'a', 'a'}));
assert "a".equals(result) : "aaaa should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'c', 'a'}));
assert "abc".equals(result) : "abca should return abc but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'b', 'b'}));
assert "ab".equals(result) : "aabb should return ab but it returns: " + result;
result = new String(removeDupes(new char[]{'a'}));
assert "a".equals(result) : "a should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'b', 'a'}));
assert "ab".equals(result) : "abba should return ab but it returns: " + result;
char[] arr = bigArr(5000000);
long startTime = System.nanoTime();
System.out.println("2: " + new String(removeDupes(arr)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Program took: " + duration + " nanoseconds");
System.out.println("Program took: " + duration/1000000000 + " seconds");
}
}
How to read and talk about the above code:
The method called removeDupes takes an array of primitive char called arr.
arr is returned as an array of primitive characters "by value". The arr passed in is garbage collected at the end of Main's member method removeDupes.
The runtime complexity of this algorithm is O(n) or more specifically O(n+(small constant)) the constant being the unique characters in the entire array of primitive chars.
The copyOfRange does not increase runtime complexity significantly since it only copies a small constant number of items. The char array called arr is not stepped all the way through.
If you pass null into removeDupes, the method returns null.
If you pass an empty array of primitive chars or an array containing one value, that unmodified array is returned.
Method removeDupes goes about as fast as physically possible, fully utilizing the L1 and L2 cache, so Branch redirects are kept to a minimum.
A 2015 standard issue unburdened computer should be able to complete this method with an primitive char array containing 500 million characters between 15 and 25 seconds.
Explain how this code works:
The first part of the array passed in is used as the repository for the unique characters that are ultimately returned. At the beginning of the function the answer is: "the characters between 0 and 1" as between 0 and tail.
We define the variable y outside of the loop because we want to find the first location where the array index that we are looking at has been duplicated in our repository. When a duplicate is found, it breaks out and quits, the y==tail returns false and the repository is not contributed to.
when the index x that we are peeking at is not represented in our repository, then we pull that one and add it to the end of our repository at index tail and increment tail.
At the end, we return the array between the points 0 and tail, which should be smaller or equal to in length to the original array.
Talking points exercise for coder interviews:
Will the program behave differently if you change the y++ to ++y? Why or why not.
Does the array copy at the end represent another 'N' pass through the entire array making runtime complexity O(n*n) instead of O(n) ? Why or why not.
Can you replace the double equals comparing primitive characters with a .equals? Why or why not?
Can this method be changed in order to do the replacements "by reference" instead of as it is now, "by value"? Why or why not?
Can you increase the efficiency of this algorithm by sorting the repository of unique values at the beginning of 'arr'? Under which circumstances would it be more efficient?
public class RemoveRepeated4rmString {
public static void main(String[] args) {
String s = "harikrishna";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
Boolean found = false;
for (int j = 0; j < s2.length(); j++) {
if (s.charAt(i) == s2.charAt(j)) {
found = true;
break; //don't need to iterate further
}
}
if (found == false) {
s2 = s2.concat(String.valueOf(s.charAt(i)));
}
}
System.out.println(s2);
}
}
public static void main(String a[]){
String name="Madan";
System.out.println(name);
StringBuilder sb=new StringBuilder(name);
for(int i=0;i<name.length();i++){
for(int j=i+1;j<name.length();j++){
if(name.charAt(i)==name.charAt(j)){
sb.deleteCharAt(j);
}
}
}
System.out.println("After deletion :"+sb+"");
}
import java.util.Scanner;
public class dublicate {
public static void main(String... a) {
System.out.print("Enter the String");
Scanner Sc = new Scanner(System.in);
String st=Sc.nextLine();
StringBuilder sb=new StringBuilder();
boolean [] bc=new boolean[256];
for(int i=0;i<st.length();i++)
{
int index=st.charAt(i);
if(bc[index]==false)
{
sb.append(st.charAt(i));
bc[index]=true;
}
}
System.out.print(sb.toString());
}
}
To me it looks like everyone is trying way too hard to accomplish this task. All we are concerned about is that it copies 1 copy of each letter if it repeats. Then because we are only concerned if those characters repeat one after the other the nested loops become arbitrary as you can just simply compare position n to position n + 1. Then because this only copies things down when they're different, to solve for the last character you can either append white space to the end of the original string, or just get it to copy the last character of the string to your result.
String removeDuplicate(String s){
String result = "";
for (int i = 0; i < s.length(); i++){
if (i + 1 < s.length() && s.charAt(i) != s.charAt(i+1)){
result = result + s.charAt(i);
}
if (i + 1 == s.length()){
result = result + s.charAt(i);
}
}
return result;
}
String str1[] ="Hi helloo helloo oooo this".split(" ");
Set<String> charSet = new LinkedHashSet<String>();
for (String c: str1)
{
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (String character : charSet)
{
sb.append(character);
}
System.out.println(sb.toString());
I think working this way would be more easy,,,
Just pass a string to this function and the job is done :) .
private static void removeduplicate(String name)
{ char[] arr = name.toCharArray();
StringBuffer modified =new StringBuffer();
for(char a:arr)
{
if(!modified.contains(Character.toString(a)))
{
modified=modified.append(Character.toString(a)) ;
}
}
System.out.println(modified);
}
public class RemoveDuplicatesFromStingsMethod1UsingLoops {
public static void main(String[] args) {
String input = new String("aaabbbcccddd");
String output = "";
for (int i = 0; i < input.length(); i++) {
if (!output.contains(String.valueOf(input.charAt(i)))) {
output += String.valueOf(input.charAt(i));
}
}
System.out.println(output);
}
}
output: abcd
You can't. You can create a new String that has duplicates removed. Why aren't you using StringBuilder (or StringBuffer, presumably)?
You can run through the string and store the unique characters in a char[] array, keeping track of how many unique characters you've seen. Then you can create a new String using the String(char[], int, int) constructor.
Also, the problem is a little ambiguous—does “duplicates” mean adjacent repetitions? (In other words, what should happen with abcab?)
Oldschool way (as we wrote such a tasks in Apple ][ Basic, adapted to Java):
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++){
for (j=i+1;j<str.length();j++){
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed non-unique symbols: " + str);
Here is another logic I'd like to share. You start comparing from midway of the string length and go backward.
Test with:
input = "azxxzy";
output = "ay";
String removeMidway(String input){
cnt = cnt+1;
StringBuilder str = new StringBuilder(input);
int midlen = str.length()/2;
for(int i=midlen-1;i>0;i--){
for(int j=midlen;j<str.length()-1;j++){
if(str.charAt(i)==str.charAt(j)){
str.delete(i, j+1);
midlen = str.length()/2;
System.out.println("i="+i+",j="+j+ ",len="+ str.length() + ",midlen=" + midlen+ ", after deleted = " + str);
}
}
}
return str.toString();
}
Another possible solution, in case a string is an ASCII string, is to maintain an array of 256 boolean elements to denote ASCII character appearance in a string. If a character appeared for the first time, we keep it and append to the result. Otherwise just skip it.
public String removeDuplicates(String input) {
boolean[] chars = new boolean[256];
StringBuilder resultStringBuilder = new StringBuilder();
for (Character c : input.toCharArray()) {
if (!chars[c]) {
resultStringBuilder.append(c);
chars[c] = true;
}
}
return resultStringBuilder.toString();
}
This approach will also work with Unicode string. You just need to increase chars size.
Solution using JDK7:
public static String removeDuplicateChars(final String str){
if (str == null || str.isEmpty()){
return str;
}
final char[] chArray = str.toCharArray();
final Set<Character> set = new LinkedHashSet<>();
for (char c : chArray) {
set.add(c);
}
final StringBuilder sb = new StringBuilder();
for (Character character : set) {
sb.append(character);
}
return sb.toString();
}
String str = "eamparuthik#gmail.com";
char[] c = str.toCharArray();
String op = "";
for(int i=0; i<=c.length-1; i++){
if(!op.contains(c[i] + ""))
op = op + c[i];
}
System.out.println(op);
public static String removeDuplicateChar(String str){
char charArray[] = str.toCharArray();
StringBuilder stringBuilder= new StringBuilder();
for(int i=0;i<charArray.length;i++){
int index = stringBuilder.toString().indexOf(charArray[i]);
if(index <= -1){
stringBuilder.append(charArray[i]);
}
}
return stringBuilder.toString();
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoveDuplicacy
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any word : ");
String s = br.readLine();
int l = s.length();
char ch;
String ans=" ";
for(int i=0; i<l; i++)
{
ch = s.charAt(i);
if(ch!=' ')
ans = ans + ch;
s = s.replace(ch,' '); //Replacing all occurrence of the current character by a space
}
System.out.println("Word after removing duplicate characters : " + ans);
}
}
public static void main(String[] args) {
int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());
for (i=0;i<str.length()-1;i++)
{
for (j=1;j<str.length();j++)
{
if (str.charAt(i)==str.charAt(j))
str.deleteCharAt(j);
}
}
System.out.println("Removed String: " + str);
}
This is improvement on solution suggested by #Dave. Here, I am implementing in single loop only.
Let's reuse the return of set.add(T item) method and add it simultaneously in StringBuffer if add is successfull
This is just O(n). No need to make a loop again.
String string = "aabbccdefatafaz";
char[] chars = string.toCharArray();
StringBuilder sb = new StringBuilder();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
if(charSet.add(c) ){
sb.append(c);
}
}
System.out.println(sb.toString()); // abcdeftz
Simple solution is to iterate through the given string and put each unique character into another string(in this case, a variable result ) if this string doesn't contain that particular character.Finally return result string as output.
Below is working and tested code snippet for removing duplicate characters from the given string which has O(n) time complexity .
private static String removeDuplicate(String s) {
String result="";
for (int i=0 ;i<s.length();i++) {
char ch = s.charAt(i);
if (!result.contains(""+ch)) {
result+=""+ch;
}
}
return result;
}
If the input is madam then output will be mad.
If the input is anagram then output will be angrm
Hope this helps.
Thanks
For the simplicity of the code- I have taken hardcore input, one can take input by using Scanner class also
public class KillDuplicateCharInString {
public static void main(String args[]) {
String str= "aaaabccdde ";
char arr[]= str.toCharArray();
int n = arr.length;
String finalStr="";
for(int i=0;i<n;i++) {
if(i==n-1){
finalStr+=arr[i];
break;
}
if(arr[i]==arr[i+1]) {
continue;
}
else {
finalStr+=arr[i];
}
}
System.out.println(finalStr);
}
}
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
String str = "";
char c;
for(int i = 0; i < s.length(); i++)
{
c = s.charAt(i);
str = str + c;
s = s.replace(c, ' ');
if(i == s.length() - 1)
{
System.out.println(str.replaceAll("\\s", ""));
}
}
}
package com.st.removeduplicate;
public class RemoveDuplicate {
public static void main(String[] args) {
String str1="shushil",str2="";
for(int i=0; i<=str1.length()-1;i++) {
int count=0;
for(int j=0;j<=i;j++) {
if(str1.charAt(i)==str1.charAt(j))
count++;
if(count >1)
break;
}
if(count==1)
str2=str2+str1.charAt(i);
}
System.out.println(str2);
}
}

How do I split strings in J2ME?

How do I split strings in J2ME in an effective way?
There is a StringTokenizer or String.split(String regex) in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).
There are a few implementations of a StringTokenizer class for J2ME. This one by Ostermiller will most likely include the functionality you need
See also this page on Mobile Programming Pit Stop for some modifications and the following example:
String firstToken;
StringTokenizer tok;
tok = new StringTokenizer("some|random|data","|");
firstToken= tok.nextToken();
There is no built in method to split strings. You have to write it on your own using
String.indexOf() and String.substring(). Not hard.
String.split(...) is available in J2SE, but not J2ME.
You are required to write your own algorithm: related post with sample solution.
I hope this one will help you... This is my own implementation i used in my application. Of course this can still be optimized. i just do not have time to do it... and also, I am working on StringBuffer here. Just refactor this to be able to use String instead.
public static String[] split(StringBuffer sb, String splitter){
String[] strs = new String[sb.length()];
int splitterLength = splitter.length();
int initialIndex = 0;
int indexOfSplitter = indexOf(sb, splitter, initialIndex);
int count = 0;
if(-1==indexOfSplitter) return new String[]{sb.toString()};
while(-1!=indexOfSplitter){
char[] chars = new char[indexOfSplitter-initialIndex];
sb.getChars(initialIndex, indexOfSplitter, chars, 0);
initialIndex = indexOfSplitter+splitterLength;
indexOfSplitter = indexOf(sb, splitter, indexOfSplitter+1);
strs[count] = new String(chars);
count++;
}
// get the remaining chars.
if(initialIndex+splitterLength<=sb.length()){
char[] chars = new char[sb.length()-initialIndex];
sb.getChars(initialIndex, sb.length(), chars, 0);
strs[count] = new String(chars);
count++;
}
String[] result = new String[count];
for(int i = 0; i<count; i++){
result[i] = strs[i];
}
return result;
}
public static int indexOf(StringBuffer sb, String str, int start){
int index = -1;
if((start>=sb.length() || start<-1) || str.length()<=0) return index;
char[] tofind = str.toCharArray();
outer: for(;start<sb.length(); start++){
char c = sb.charAt(start);
if(c==tofind[0]){
if(1==tofind.length) return start;
inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
char find = tofind[i];
int currentSourceIndex = start+i;
if(currentSourceIndex<sb.length()){
char source = sb.charAt(start+i);
if(find==source){
if(i==tofind.length-1){
return start;
}
continue inner;
} else {
start++;
continue outer;
}
} else {
return -1;
}
}
}
}
return index;
}
That depends on what exactly you want to achieve, but the function String.substring() will be in there somewhere:
String myString = "Hello World";
This will print the substring starting from index 6 to the end of the string:
System.out.println(myString.substring(6));
This will print the substring starting from index 0 until index 5:
System.out.println(myString.substring(0,5));
Output of all the code above:
World
Hello
Combine this with the other String functions (indexOf(). etc.) to achieve the desired effect!
Re-reading your question, it looks as though you may have been looking for String.split(). This will split your input string into an array of strings based on a given regex:
String myString = "Hi-There-Gang";
String[] splitStrings = myString.split("-");
This will result in the splitStrings array containing three string, "Hi", "There" and "Gang".
Re-reading your question again, String.split is not available in J2ME, but the same effect can be achieved with substring and indexOf.
public static Vector splitDelimiter(String text, char delimiter) {
Vector splittedString = null;
String text1 = "";
if (text != null) {
splittedString = new Vector();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == delimiter) {
splittedString.addElement(text1);
text1 = "";
} else {
text1 += text.charAt(i);
// if(i==text.length()-1){
// splittedString.addElement(text1);
// }
}
}
splittedString.addElement(text1);
}
return s
}
You can use this method for splitting a delimiter.
In J2ME no split, but you can use this code for split.This code works with only 1 simbol delimiter!!!
Use NetBeans.File\Create Project\ Java ME\ MobileApplication\Set project name(split)\Set checkmark.Delete all code in your (Midlet.java).Copy this code and past in your (Midlet.java).
//IDE NetBeans 7.3.1
//author: UserSuperPupsik
//email: usersuperpupsik#gmail.com
package split;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Vector;
public class Midlet extends MIDlet {
public String e1;
public Vector v=new Vector();
public int ma;
int IsD=0;
int vax=0;
public String out[];
private Form f;
public void split0(String text,String delimiter){
if (text!=""){
IsD=0;
int raz=0;
//v.removeAllElements();
v.setSize(0);
int io;
String temp="";
int ni=(text.length()-1);
for(io=0;io<=ni;io++){
char ch=text.charAt(io);
String st=""+ch;
if(io==0 && st.equals(delimiter)){IsD=1;}
if(!st.equals(delimiter)){temp=temp+st;} //Not equals (!=)
else if(st.equals(delimiter)&&temp!="")//equals (==)
{
IsD=1;
//f.append(temp);
v.addElement(temp);
temp="";
}
if(io==ni && temp!="") {
v.addElement(temp);
temp="";
}
if((io==ni)&&IsD==0&&temp!=""){v.addElement(temp);}
}
if(v.size()!=0){
ma=(v.size());
out=new String[ma];
v.copyInto(out);
}
//else if(v.size()==0){IsD=1; }
}
}
public void method1(){
f.append("\n");
f.append("IsD: " +IsD+"");
if (v.size()!=0){
for( vax=0;vax<=ma-1;vax++){
f.append("\n");
f.append(out[vax]);
}
}
}
public void startApp() {
f=new Form("Hello J2ME!");
Display.getDisplay(this).setCurrent(f);
f.append("");
split0("Hello.World.Good...Luck.end" , ".");
method1();
split0(".",".");
method1();
split0(" First WORD2 Word3 "," ");
method1();
split0("...",".");
method1();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Splited elements located in array called (out).For Example out[1]:Hello.
Good Luck!!!
Another alternative solution:
public static Vector split(String stringToSplit, String separator){
if(stringToSplit.length<1){
return null;
}
Vector stringsFound = new Vector();
String remainingString = stringToSplit;
while(remainingString.length()>0){
int separatorStartingIndex = remainingString.indexOf(separator);
if(separatorStartingIndex==-1){
// Not separators found in the remaining String. Get substring and finish
stringsFound.addElement(remainingString);
break;
}
else{
// The separator is at the beginning of the String,
// Push the beginning at the end of separator and continue
if(remainingString.startsWith(separator)){
remainingString = remainingString.substring(separator.length());
}
// The separator is present and is not the beginning, add substring and continue
else{
stringsFound.addElement(remainingString.substring(0, separatorStartingIndex));
remainingString = remainingString.substring(separatorStartingIndex + separator.length());
}
}
}
return stringsFound;
}

Categories