Convert array of Strings to String - java

Hello i have a little problem with array conversion
i want to convert this array format ["x","z","y"] To this String Format ('x','y','z') with commas and parentheses.
btw this array is dynamic in size may be increased or decreased
this is my try
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String [] arr = {"x","y","z"};
String s = "(";
for(int i = 0; i <arr.length;i++){
s +="'".concat(arr[i]).concat("'") + ',' ;
if(i == arr.length-1)
s.replace(',', ')');
}
System.out.print(s);
}
this is my output ('x','y','z',
i want to replace the last comma with ')'

This also will do the magic..
Please use StringBuilder for these kind of string operations..
for (int i = 0; i < arr.length; i++) {
s += "'".concat(arr[i]).concat("'") + ',';
}
s = s.concat(")");
System.out.print(s.replace(",)", ")"));

s.replace(',', ')');
Here you are trying to replace the comma, but Strings in java are immutable, it means you are in fact replacing this, but not assigning the value to any variable, so it's pointless. Also, that replace will not do what you think. Instead, you need to:
s = s.substring(0, s.length()-1);
This is gonna remove the last character from the String (that is extra comma at the end). Then just append ) to it and you are done.

You can also use the String.join method :
public static void main(String[] args) {
String [] arr = {"x","y","z"};
String s = String.join("','", arr);
s = "('"+s+"')";
System.out.print(s);
}

You can try this, using String.format and String.join
String[] arr = { "x", "y", "z" };
String s = String.format("('%s')", String.join("','", arr));
System.out.println(s);
It print
('x','y','z')
Edit
If you are using jdk7, you can use StringBuilder to avoid performance issues, as shown in the code:
String[] a = { "x", "y", "z" };
StringBuilder b = new StringBuilder("(");
for (int i = 0; i < a.length; i++) {
b.append("'").append(String.valueOf(a[i])).append("'");
b.append((i == a.length - 1) ? ")" : ", ");
}
System.out.println(b);
It print
('x','y','z')

Related

split a string when there is a change in character without a regular expression

There is a way to split a string into repeating characters using a regex function but I want to do it without using it.
for example, given a string like: "EE B" my output will be an array of strings e.g
{"EE", " ", "B"}
my approach is:
given a string I will first find the number of unique characters in a string so I know the size of the array. Then I will change the string to an array of characters. Then I will check if the next character is the same or not. if it is the same then append them together if not begin a new string.
my code so far..
String myinput = "EE B";
char[] cinput = new char[myinput.length()];
cinput = myinput.toCharArray(); //turn string to array of characters
int uniquecha = myinput.length();
for (int i = 0; i < cinput.length; i++) {
if (i != myinput.indexOf(cinput[i])) {
uniquecha--;
} //this should give me the number of unique characters
String[] returninput = new String[uniquecha];
Arrays.fill(returninput, "");
for (int i = 0; i < uniquecha; i++) {
returninput[i] = "" + myinput.charAt(i);
for (int j = 0; j < myinput.length - 1; j++) {
if (myinput.charAt(j) == myinput.charAt(j + 1)) {
returninput[j] += myinput.charAt(j + 1);
} else {
break;
}
}
} return returninput;
but there is something wrong with the second part as I cant figure out why it is not beginning a new string when the character changes.
You question says that you don't want to use regex, but I see no reason for that requirement, other than this is maybe homework. If you are open to using regex here, then there is a one line solution which splits your input string on the following pattern:
(?<=\S)(?=\s)|(?<=\s)(?=\S)
This pattern uses lookarounds to split whenever what precedes is a non whitespace character and what proceeds is a whitespace character, or vice-versa.
String input = "EE B";
String[] parts = input.split("(?<=\\S)(?=\\s)|(?<=\\s)(?=\\S)");
System.out.println(Arrays.toString(parts));
[EE, , B]
^^ a single space character in the middle
Demo
If I understood correctly, you want to split the characters in a string so that similar-consecutive characters stay together. If that's the case, here is how I would do it:
public static ArrayList<String> splitString(String str)
{
ArrayList<String> output = new ArrayList<>();
String combo = "";
//iterates through all the characters in the input
for(char c: str.toCharArray()) {
//check if the current char is equal to the last added char
if(combo.length() > 0 && c != combo.charAt(combo.length() - 1)) {
output.add(combo);
combo = "";
}
combo += c;
}
output.add(combo); //adds the last character
return output;
}
Note that instead of using an array (has a fixed size) to store the output, I used an ArrayList, which has a variable size. Also, instead of checking the next character for equality with the current one, I preferred to use the last character for that. The variable combo is used to temporarily store the characters before they go to output.
Now, here is one way to print the result following your guidelines:
public static void main(String[] args)
{
String input = "EEEE BCD DdA";
ArrayList<String> output = splitString(input);
System.out.print("[");
for(int i = 0; i < output.size(); i++) {
System.out.print("\"" + output.get(i) + "\"");
if(i != output.size()-1)
System.out.print(", ");
}
System.out.println("]");
}
The output when running the above code will be:
["EEEE", " ", "B", "C", "D", " ", "D", "d", "A"]

How to add multiple characters to one index in a Char Array?

Im currently trying to create a function where my input is a string such as "AABBCCDDEE" and the function outputs a String array "AA""BB""CC" and so on.
public static char[] stringSplitter(final String input) {
String[] strarray = new String[input.length()];
if (input == null) {
return null;
}
char[] chrarray = input.toCharArray();
char[] outputarray = new char[input.length()];
int j = 0;
for (int i = 0; i < chrarray.length; i++) {
char chr = chrarray[i];
System.out.print(chr);
outputarray[j] = chrarray[i]; //here i need to find a way to add the characters to the index at j if the preceding characters are equal
if (i + 1 < input.length() && chrarray[i + 1] != chr) {
j++;
outputarray[j] = chrarray[i + 1];
System.out.println(" ");
}
}
}
Arrays are fixed-length, so you can't do this with an array unless you allocate one with sufficient extra room up-front (which would require a pass through the string to find out how much extra room you needed).
Instead, consider using a StringBuilder for the output, which you can convert into a char array when you're done.
If I understood correctly, you want to split the characters in a string so that similar-consecutive characters stay together. If that's the case, here is how I would do it:
public static ArrayList<String> splitString(String str) {
ArrayList<String> output = new ArrayList<>();
String combo = "";
//iterates through all the characters in the input
for(char c: str.toCharArray()) {
//check if the current char is equal to the last added char
if(combo.length() > 0 && c != combo.charAt(combo.length() - 1)) {
output.add(combo);
combo = "";
}
combo += c;
}
output.add(combo); //adds the last character
return output;
}
Note that instead of using an array (has a fixed size) to store the output, I used an ArrayList, which has a variable size. Also, note that it's a list of strings (stores strings), not characters. The reason for this is that if it was a list of characters I wouldn't be able to store more than one character in the same index.
In each iteration of the loop, I check for equality between the current character and it's consecutive. The variable combo is used to temporarily store the characters (in a string) before they go to output.
Now, to print the results in a clear way:
public static void main(String[] args)
{
String input = "EEEE BCD DdA";
ArrayList<String> output = splitString(input);
System.out.print("[");
for(int i = 0; i < output.size(); i++) {
System.out.print("\"" + output.get(i) + "\"");
if(i != output.size()-1)
System.out.print(", ");
}
System.out.println("]");
}
The output when running the above code will be:
["EEEE", " ", "B", "C", "D", " ", "D", "d", "A"]
You can use an ArrayList of type String to store the consecutive letter Strings after splitting them. This code should work for you.
import java.util.*;
public class StringSplitter{
static ArrayList<String> splitString(String str)
{
ArrayList<String> result_list= new ArrayList<String>();
int last_index;
if(str == null)
{
return null;
}
else
{
while(str.length() != 0)
{
last_index = str.lastIndexOf(str.charAt(0));
result_list.add(str.substring(0, last_index+1));
str = str.substring(last_index+1);
}
}
return result_list;
}
public static void main(String[] args)
{
ArrayList<String> result = splitString("AABBCCDDEEE");
System.out.println(result);
}
}
I have used an ArrayList because it does not require you to fix a size while declaration.

Joining a String using a delimiter only at certain points

I'm trying to join an array of Strings using the String.join() method. I need the first item of the array to be removed (or set to empty). If I have a string array such as {"a","b","c","d"}, I want to return only b.c.d.
If it can be done with a for loop, that is fine. I currently have:
for (int i=1; i<item.length; i++) {
newString += item[i] + ".";
}
Try using Arrays.copyOfRange to skip the first element of the array:
String.join(".", Arrays.copyOfRange(item, 1, item.length));
Demo
You can do it as follows:
String.join(".", Arrays.stream(myArray, 1, myArray.length).collect(Collectors.toList()));
or if you want the . suffix in the result then use joining collector:
Arrays.stream(myArray, 1, myArray.length)
.collect(Collectors.joining(".","","."));
An alternative with streams:
String result = Arrays.stream(item)
.skip(1)
.collect(joining("."));
Or this can also be a possible answer
String.join(".",myarray).substring(myarray[0].length()+1);
try this
String[] a = new String[] {"a","b","c","d"};
String newString = "";
for (int i=1; i<a.length; i++) {
if (i > 0) {
newString += a[i] + ".";
}
}
System.out.println(newString);
try using following code
public static String getJoined(String []strings) {
StringBuilder sbr = new StringBuilder(); // to store joined string
// skip first string, iterate over rest of the strings.
for(int i=1; i<strings.length; i++) {
// append current string and '.'
sbr.append(strings[i]).append(".");
}
// remove last '.' , it will not be required.
// if not deleted the result will be contain '.' at end.
// e.g for {"a","b","c"} the result will be "b.c." instead of "b.c"
sbr.delete(sbr.length()-1, sbr.length());
return sbr.toString();
}

Remove characters at certain position at string

I want to remove certain characters at specific positions of the String. I have the positions, but I am facing problems removing the characters.
what i am doing is:
if (string.subSequence(k, k + 4).equals("\n\t\t\t")){
string = string.subSequence(0, k) + "" + s.subSequence(k, s.length());
}
I need to remove "\n\t\t\t" from string
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.delete(start, end);
sb.deleteCharAt(index);
String result = sb.toString();
Use StringBuilder
String str=" ab a acd";
StringBuilder sb = new StringBuilder(str);
sb.delete(0,3);
sb.deleteCharAt(0);
String result = sb.toString();
System.out.println(result);
public static String remove(int postion, String stringName) {
char [] charArray = stringName.toCharArray();
char [] resultArray = new char[charArray.length];
int count = 0;
for (int i=0; i< charArray.length; i++) {
if (i != postion-1) {
resultArray[count] = charArray[i];
count++;
}
}
return String.valueOf(resultArray);
}
Use String.ReplaceAll() instead of this.
But if you only want to remove specific element only you can use substring().
Now you want to know position which you already know.
Put your points in a HashSet called set
StringBuilder sb=new StringBuilder();
for(int i=0;i<string.length();i++){
if(!set.contains(string.charAt(i)))
sb.append(string.charAt(i));
}
String reformattedString=sb.toString();
First you have to put \ in front of the special characters in order to do the matching of the two string, thus you will have .equals("\"\\n\\t\\t\\t\""), otherwise the substring is not going to be recognized inside the string. Then the other thing which you have to fix is the position of the index begin and end inside .subSequence(k,k+10) since the first and the last character are 10 positions apart and not 4. Note also that when you patch the string you go from position 0 to k and from k+10 to str.length(). If you go from 0 --> k and k --> length() you just join the old string together :).
Your code should work like this, I have tested it already
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
}
also you don't need +" "+ since you are adding strings. Whoever wants to see the effect of this can run this simple code:
public class ReplaceChars_20354310_part2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";
System.out.println(str); //print str
System.out.println(ReplaceChars(str)); //then print after you replace the substring
System.out.println("\n"); //skip line
String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str
System.out.println(str2); //then print after you replace the substring
System.out.println(ReplaceChars(str2));
}
//Method ReplaceChars
public static String ReplaceChars (String str) {
String newstr ="";
int k;
k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string starts within the larger string
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str
}
return newstr;
}//end method
}

How can I split a string in to multiple parts?

I have a string with several words separated by spaces, e.g. "firstword second third", and an ArrayList. I want to split the string into several pieces, and add the 'piece' strings to the ArrayList.
For example,"firstword second third" can be split to three separate strings , so the ArrayList would have 3 elements; "1 2 3 4" can be split into 4 strings, in 4 elements of the ArrayList. See the code below:
public void separateAndAdd(String notseparated) {
for(int i=0;i<canBeSepartedinto(notseparated);i++{
//what should i put here in order to split the string via spaces?
thearray.add(separatedstring);
}
}
public int canBeSeparatedinto(String string)
//what do i put here to find out the amount of spaces inside the string?
return ....
}
Please leave a comment if you dont get what I mean or I should fix some errors in this post. Thanks for your time!
You can split the String at the spaces using split():
String[] parts = inputString.split(" ");
Afterwards iterate over the array and add the individual parts (if !"".equals(parts[i]) to the list.
If you want to split on one space, you can use .split(" ");. If you want to split on all spaces in a row, use .split(" +");.
Consider the following example:
class SplitTest {
public static void main(String...args) {
String s = "This is a test"; // note two spaces between 'a' and 'test'
String[] a = s.split(" ");
String[] b = s.split(" +");
System.out.println("a: " + a.length);
for(int i = 0; i < a.length; i++) {
System.out.println("i " + a[i]);
}
System.out.println("b: " + b.length);
for(int i = 0; i < b.length; i++) {
System.out.println("i " + b[i]);
}
}
}
If you are worried about non-standard spaces, you can use "\\s+" instead of " +", as "\\s" will capture any white space, not just the 'space character'.
So your separate and add method becomes:
void separateAndAdd(String raw) {
String[] tokens = raw.split("\\s+");
theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
for(String s : tokens) {
theArray.add(s);
}
}
Here's a more complete example - note that there is a small modification in the separateAndAdd method that I discovered during testing.
import java.util.*;
class SplitTest {
public static void main(String...args) {
SplitTest st = new SplitTest();
st.separateAndAdd("This is a test");
st.separateAndAdd("of the emergency");
st.separateAndAdd("");
st.separateAndAdd("broadcast system.");
System.out.println(st);
}
ArrayList<String> theArray = new ArrayList<String>();
void separateAndAdd(String raw) {
String[] tokens = raw.split("\\s+");
theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
for(String s : tokens) {
if(!s.isEmpty()) theArray.add(s);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(String s : theArray)
sb.append(s).append(" ");
return sb.toString().trim();
}
}
I would suggest using the
apache.commons.lang.StringUtils library.
It is the easiest and covers all the different conditions you can want int he spliting up of a string with minimum code.
Here is a reference to the split method :
Split Method
you can also refer to the other options available for the split method on the same link.
Do this:
thearray = new ArrayList<String>(Arrays.asList(notseparated.split(" ")));
or if thearray already instantiated
thearray.addAll(Arrays.asList(notseparated.split(" ")));
If you want to split the string in different parts, like here i am going to show you that how i can split this string 14-03-2016 in day,month and year.
String[] parts = myDate.split("-");
day=parts[0];
month=parts[1];
year=parts[2];
You can do that using .split() try this
String[] words= inputString.split("\\s");
try this:
string to 2 part:
public String[] get(String s){
int l = s.length();
int t = l / 2;
String first = "";
String sec = "";
for(int i =0; i<l; i++){
if(i < t){
first += s.charAt(i);
}else{
sec += s.charAt(i);
}
}
String[] result = {first, sec};
return result;
}
example:
String s = "HelloWorld";
String[] res = get(s);
System.out.println(res[0]+" "+res[1])
output:
Hello World

Categories

Resources