Sort a single String in Java - java

Is there a native way to sort a String by its contents in java? E.g.
String s = "edcba" -> "abcde"

toCharArray followed by Arrays.sort followed by a String constructor call:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.

No there is no built-in String method. You can convert it to a char array, sort it using Arrays.sort and convert that back into a String.
String test= "edcba";
char[] ar = test.toCharArray();
Arrays.sort(ar);
String sorted = String.valueOf(ar);
Or, when you want to deal correctly with locale-specific stuff like uppercase and accented characters:
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
public class Test
{
public static void main(String[] args)
{
Collator collator = Collator.getInstance(new Locale("fr", "FR"));
String original = "éDedCBcbAàa";
String[] split = original.split("");
Arrays.sort(split, collator);
String sorted = "";
for (int i = 0; i < split.length; i++)
{
sorted += split[i];
}
System.out.println(sorted); // "aAàbBcCdDeé"
}
}

In Java 8 it can be done with:
String s = "edcba".chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:
import java.util.stream.Collectors;
import java.util.stream.Stream;
String sorted =
Stream.of("edcba".split(""))
.sorted()
.collect(Collectors.joining());

Convert to array of chars → Sort → Convert back to String:
String s = "edcba";
char[] c = s.toCharArray(); // convert to array of chars
java.util.Arrays.sort(c); // sort
String newString = new String(c); // convert back to String
System.out.println(newString); // "abcde"

A more raw approach without using sort Arrays.sort method.
This is using insertion sort.
public static void main(String[] args){
String wordSt="watch";
char[] word=wordSt.toCharArray();
for(int i=0;i<(word.length-1);i++){
for(int j=i+1;j>0;j--){
if(word[j]<word[j-1]){
char temp=word[j-1];
word[j-1]=word[j];
word[j]=temp;
}
}
}
wordSt=String.valueOf(word);
System.out.println(wordSt);
}

String a ="dgfa";
char [] c = a.toCharArray();
Arrays.sort(c);
return new String(c);
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.

Procedure :
At first convert the string to char array
Then sort the array of character
Convert the character array to string
Print the string
Code snippet:
String input = "world";
char[] arr = input.toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
System.out.println(sorted);

str.chars().boxed().map(Character::toString).sorted().collect(Collectors.joining())
or
s.chars().mapToObj(Character::toString).sorted().collect(Collectors.joining())
or
Arrays.stream(str.split("")).sorted().collect(Collectors.joining())

Question: sort a string in java
public class SortAStringInJava {
public static void main(String[] args) {
String str = "Protijayi";
// Method 1
str = str.chars() // IntStream
.sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
System.out.println(str);
// Method 2
str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
System.out.println(str);
}
}

A solution that uses the Stream API and also handles Unicode supplementary characters:
public static String sort(final String s) {
return s.codePoints()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}

You can also write up a counting sort algorithm to sort all the characters in an array if you would like to reduce your worst-case time complexity from nlogn to n

public static void main(String[] args) {
String str = "helloword";
char[] arr;
List<Character> l = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
arr = str.toCharArray();
l.add(arr[i]);
}
Collections.sort(l);
str = l.toString();
System.out.println(str);
str = str.replaceAll("\\[", "").replaceAll("\\]", "")
.replaceAll("[,]", "");
System.out.println(str);
}

Without using Collections in Java:
import java.util.Scanner;
public class SortingaString {
public static String Sort(String s1)
{
char ch[]=s1.toCharArray();
String res=" ";
for(int i=0; i<ch.length ; i++)
{
for(int j=i+1;j<ch.length; j++)
{
if(ch[i]>=ch[j])
{
char m=ch[i];
ch[i]=ch[j];
ch[j]=m;
}
}
res=res+ch[i];
}
return res;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the string");
String s1=sc.next();
String ans=Sort( s1);
System.out.println("after sorting=="+ans);
}
}
Output:
enter the string==
sorting
after sorting== ginorst

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

(Java) Append elements to a String variable from String array up to specific index?

public class sample {
public static void main(String[] args) {
String[] test = new String[1024];
int count = 0;
test[count] = "33";
count++;
test[count] = "34";
String s = new String();
This is just a simplified version, but I would like to append elements to a String variable s up to the index value of count without using StringBuilder, is there a way to do it? Thank you.
edit: without using loop as well, is there a String manipulation function I can use?
One way to do that is using String.join and Arrays.copyOf:
String s = String.join("", Arrays.copyOf(test, count + 1));
Which, with your test data, produces 3334
Dont quite understand what you want...
But I guess you could user char array?
char[] c = new char[maxCount]
for(int i = 0;i<maxCount;i++){
c[i] = "34";
}
String s = String.valueOf(c)
Hope this could help you:)
Hard to say, what you're asking for...
Concatenating consecutive numbers could be easily done with a stream:
String s = IntStream.rangeClosed(0, 1024)
.mapToObj(Integer::toString)
.collect(Collectors.joining());
We can use the join function of String.
Assuming the test is the string array.
String joinedString = String.join("", Arrays.stream(test).limit(count).collect(Collectors.toList()))
You can use String.join()
public class Main {
public static void main(String[] args) {
String[] test = new String[1024];
int count = 0;
test[count] = "33";
count++;
test[count] = "34";
String s = new String();
System.out.println(s=String.join("", Arrays.copyOf(test, count + 1)));
}
}

How to convert string of numbers into int array in java

I have an input String of "0102030405" how can I split this number by two so that it would have an output of String[] ("01", "02", "03", "04", "05").
Try this,
String a = "0102030405";
System.out.println(Arrays.toString(a.split("(?<=\\G.{2})")));
String input = "0102030405";
String[] output = new String[input.length()/2];
int k=0;
for(int i=0;i<input.length();i+=2){
output[k++] = input.substring(i, i+2);
}
for(String s:output){
System.out.println(s);
}
You could try something like reading each two characters from a string.
This could be solved by: "(?<=\\G.{2})"
But I think a cleaner solution is this:
string.substring(startStringInt, endStringInt);
Here is a complete example:
package Main;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : splitString("0102030405", 2)) {
System.out.println(part);
}
}
private static List<String> splitString(String string, int numberOfChars) {
List<String> result = new ArrayList<String>();
for (int i = 0; i < string.length(); i += numberOfChars)
{
result.add(string.substring(i, Math.min(string.length(), i + numberOfChars)));
}
return result;
}
}
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
HelloWorld h1 = new HelloWorld();
String a = "0102030405";
System.out.println(h1.getSplitString(a));
}
private ArrayList<String> getSplitString(String stringToBeSplitted) {
char[] charArray = stringToBeSplitted.toCharArray();
int stringLength = charArray.length;
ArrayList<String> outPutArray = new ArrayList<String>();
for(int i=0; i <= stringLength-2; i+=2){
outPutArray.add("" + charArray[i] + charArray[i+1]);
}
return outPutArray;
}
}
Here the String is first split into a char array. Then using a for loop two digits are concatenated and put into a ArrayList to return. If you need an Array to return you can change the return type to String[] and in the return statement change it to
outPutArray.toArray(new String[outPutArray.size()];
If you insert a string has odd number of characters last character will be omitted. Change the loop condition to fix that.

How to convert ArrayList of Strings to char array

The following code converts ArrayList<String> to char[] and print output which appears as [back, pack]. Here, the char[] includes ',' and ' '. Is there a way to do it in another way to get rid of comma and space?
ArrayList<String> list = new ArrayList<String>();
list.add("back");
list.add("pack");
char[] chars = list.toString().toCharArray();
for (char i : chars){
System.out.print(i);
}
Just replace the this line
char[] chars = list.toString().toCharArray();
with below two lines
String str=list.toString().replaceAll(",", "");
char[] chars = str.substring(1, str.length()-1).replaceAll(" ", "").toCharArray();
You can do it by joining the Strings in your ArrayList<String> and then getting char[] from the result:
char[] chars = list.stream().collect(Collectors.joining()).toCharArray();
Here .stream.collect(Collectors.joining()) part is Java 8 Stream way to join a sequence of Strings into one. See: Collectors.joining() docs.
If you want any delimiter between the parts in the result, use Collectors.joining(delimiter) instead.
There's also an overload which adds prefix and suffix to the result, for example, if you want [ and ] in it, use Collectors.joining("", "[", "]").
String to charArray in Java Code:
ArrayList<String> list = new ArrayList<String>();
ArrayList<Character> chars = new ArrayList<Character>();
list.add( "back" );
list.add( "pack" );
for ( String string : list )
{
for ( char c : string.toCharArray() )
{
chars.add( c );
}
}
System.out.println( chars );
Your toString method on list is what is adding the comma and space, it's a String representation of your list. As list is a collection of Strings you don't need to call toString on it, just iterate through the collection converting each String into an array of chars using toCharArray (I assume you will probably want to add all the chars of all the Strings together).
Just an example how should you resolved large list to array copy. Beware number of characters must be less then Integer.MAX. This code is just an example how it could be done. There are plenty of checks that one must implement it to make that code works properly.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class WrappedList {
//Or replace with some better counter
int totalCharCount = 0;
final List<String> list;
public WrappedList() {
this(new ArrayList<String>());
}
public WrappedList(final List<String> list) {
this.list = list;
}
public void add(final String toAdd) {
if(toAdd != null) {
totalCharCount += toAdd.length();
this.list.add(toAdd);
}
}
public List<String> getList() {
return Collections.unmodifiableList(list);
}
public char[] toCharArray() {
return this.toCharArray(this.totalCharCount);
}
public char[] toCharArray(final int charCountToCopy) {
final char[] product = new char[charCountToCopy];
int buffered = 0;
for (String string : list) {
char[] charArray = string.toCharArray();
System.arraycopy(charArray, 0, product, buffered, charArray.length);
buffered += charArray.length;
}
return product;
}
//Utility method could be used also as stand-alone class
public char[] toCharArray(final List<String> all) {
int size = all.size();
char[][] cpy = new char[size][];
for (int i = 0; i < all.size(); i++) {
cpy[i] = all.get(i).toCharArray();
}
int total = 0;
for (char[] cs : cpy) {
total += cs.length;
}
return this.toCharArray(total);
}
public static void main(String[] args) {
//Add String iteratively
WrappedList wrappedList = new WrappedList();
wrappedList.add("back");
wrappedList.add("pack");
wrappedList.add("back1");
wrappedList.add("pack1");
final char[] charArray = wrappedList.toCharArray();
System.out.println("Your char array:");
for (char c : charArray) {
System.out.println(c);
}
//Utility method one time for all, should by used in stand-alone Utility class
System.out.println("As util method");
System.out.println(wrappedList.toCharArray(wrappedList.getList()));
}
}
See also: system-arraycopy-than-a-for-loop-for-copying-arrays

How to remove duplicate letters with a loop ( either for or while ) loop

Language : Java
Key Notes: *Needs to loop through a String using either a For loop or While loop
*It removes the duplicate letter(s) of the String and returns the word without the dupilcates.
Eg: The string is HELLO - The method then loops through and removes any duplicates, in this case " L " and returns in the end HELO
i have this so far
private String removeAnyDuplicates(String userWord)
{
//Code goes here?
return "" ; // Need to return the new string
}
You can do that with regular expressions. e.g.:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(.)\\1*");
public static void main(String[] args) {
String input = "HELLO, AABBCC";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("$1")
); // prints "HELO, ABC"
}
I'm assuming that removing duplicates means that the result contains at most one occurrence of any character. (Some of the other answers assume that adjacent duplicates only need to be reduced to single occurrences.) The basic algorithm would be:
initialize the result to the empty string
loop through each character of the input and if the character is not already present in the result, append it to the result
return the result
A naive (and very inefficient) implementation would be:
private String removeAnyDuplicates(String userWord)
{
String result = "";
for (int i = 0; i < userWord.length(); ++i) {
char c = result.charAt(i);
if (result.indexOf(c) < 0) {
// negative index indicates not present
result += String.valueOf(c);
}
}
return result;
}
This has two major sources of inefficiency: it creates many intermediate String objects and it has to scan the entire result so far for each character of the input. These problems can be solved by using some other built-in Java classes—a StringBuilder to more efficiently accumulate the result and a Set implementation to efficiently record and test which characters have already been seen:
private String removeAnyDuplicates(String userWord)
{
int len = userWord.length();
StringBuilder result = new StringBuilder(len);
Set<Character> unique = new HashSet<Character>();
for (int i = 0; i < len; ++i) {
char c = result.charAt(i);
// try to add c to set of unique characters
if (unique.add(c)) {
// if it succeeds, this is the first time seeing c
result.append(c);
}
}
return result.toString();
}
private String removeAnyDuplicates(String userWord)
{
CharSequence inputStr = userWord;
int length = inputStr.length();
Set<Character> uniqueChars = new HashSet<Character>();
for(int i=0; i < length; ++i) {
uniqueChars.add(inputStr.charAt(i));
}
return uniqueChars.size() >= 3;
}
check out this answer
Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates.
Like this:
private static String removeAnyDuplicates(String userWord)
{
char[] chars = userWord.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);
}
return sb.toString();
}
Remember:
import java.util.LinkedHashSet;
import java.util.Set;
You can try this
public static void main(String args[]){
System.out.println(removeAnyDuplicates("HELLO"));
}
private static String removeAnyDuplicates(String userWord)
{
char[] arr=userWord.toCharArray();
List<String> list=new ArrayList<>();
for(int i=0;i<arr.length;i++){
if(!list.contains(String.valueOf(arr[i]))){
list.add(String.valueOf(arr[i]));
}
}
return list.toString().replaceAll("\\[|\\]|\\,","") ;
}
Try this one liner:
private String removeAnyDuplicates(String userWord) {
return userWord.replaceAll("(.)\\1+", "$1");
}
This uses a regular expression to find repeated (2 or more) letters and replaces them with a single instance of the letter.
It is unclear if "repeated" means appearing immediately after or anywhere after. For anywhere, use this:
private String removeAnyDuplicates(String userWord) {
return userWord.replaceAll("(.)(?=.*\\1)", "");
}

Categories