Joining a String using a delimiter only at certain points - java

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();
}

Related

How to reverse a String after a comma and then print the 1st half of the String Java

For example String grdwe,erwd becomes dwregrdwe
I have most of the code I just have trouble accessing all of ch1 and ch2 in my code after my for loop in my method I think I have to add all the elements to ch1 and ch2 into two separate arrays of characters but I wouldn't know what to initially initialize the array to it only reads 1 element I want to access all elements and then concat them. I'm stumped.
And I'd prefer to avoid Stringbuilder if possible
public class reverseStringAfterAComma{
public void reverseMethod(String word){
char ch1 = ' ';
char ch2 = ' ';
for(int a=0; a<word.length(); a++)
{
if(word.charAt(a)==',')
{
for(int i=word.length()-1; i>a; i--)
{
ch1 = word.charAt(i);
System.out.print(ch1);
}
for (int j=0; j<a; j++)
{
ch2 = word.charAt(j);
System.out.print(ch2);
}
}
}
//System.out.print("\n"+ch1);
//System.out.print("\n"+ch2);
}
public static void main(String []args){
reverseStringAfterAComma rsac = new reverseStringAfterAComma();
String str="grdwe,erwd";
rsac.reverseMethod(str);
}
}
You can use string builder as described here:
First split the string using:
String[] splitString = yourString.split(",");
Then reverse the second part of the string using this:
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
then append the two sections like so:
String final = splitString[1] + splitString[0];
And if you want to print it just do:
System.out.print(final);
The final code would be:
String[] splitString = yourString.split(",");
splitString[1] = new StringBuilder(splitString[1]).reverse().toString();
String final = splitString[1] + splitString[0];
System.out.print(final);
Then, since you are using stringbuilder all you need to do extra, is import it by putting this at the top of your code:
import java.lang.StringBuilder;
It appears you currently have working code, but are looking to print/save the value outside of the for loops. Just set a variable before you enter the loops, and concatenate the chars in each loop:
String result = "";
for (int a = 0; a < word.length(); a++) {
if (word.charAt(a) == ',') {
for (int i = word.length() - 1; i > a; i--) {
ch1 = word.charAt(i);
result += ch1;
}
for (int j = 0; j < a; j++) {
ch2 = word.charAt(j);
result += ch2;
}
}
}
System.out.println(result);
Demo
Let propose a solution that doesn't use a StringBuilder
You should knoz there is no correct reason not to use that class since this is well tested
The first step would be to split your String on the first comma found (I assumed, in case there is more than one, that the rest are part of the text to reverse). To do that, we can you String.split(String regex, int limit).
The limit is define like this
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n and the array's last entry will contain all input beyond the last matched delimiter.
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example :
"foobar".split(",", 2) // {"foobar"}
"foo,bar".split(",", 2) // {"foo", "bar"}
"foo,bar,far".split(",", 2) // {"foo", "bar,far"}
So this could be used at our advantage here :
String text = "Jake, ma I ,dlrow olleh";
String[] splittedText = text.split( ",", 2 ); //will give a maximum of a 2 length array
Know, we just need to reverse the second array if it exists, using the simplest algorithm.
String result;
if ( splittedText.length == 2 ) { //A comma was found
char[] toReverse = splittedText[1].toCharArray(); //get the char array to revese
int start = 0;
int end = toReverse.length - 1;
while ( start < end ) { //iterate until needed
char tmp = toReverse[start];
toReverse[start] = toReverse[end];
toReverse[end] = tmp;
start++; //step forward
end--; //step back
}
result = new String( toReverse ) + splittedText[0];
}
This was the part that should be done with a StringBuilder using
if ( splittedText.length == 2 ){
result = new StringBuilder(splittedText[1]).reverse().toString() + splittedText[0];
}
And if there is only one cell, the result is the same as the original text
else { //No comma found, just take the original text
result = text;
}
Then we just need to print the result
System.out.println( result );
hello world, I am Jake

Convert array of Strings to String

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')

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
}

What is the better way to add commas to multiple elements string output?

I need to put comma separated values into ourOutput (for future output). So, what I need is to add commas and remove last unnecessary comma or check if comma should be placed.
I came to two following solutions:
1st approach:
ourOutput = ''<<'';
for (int i = 0; i< 10, i++) {
if (/*some condition goes here*/) {
if (ourOutput.size() == 0) {
ourOutput << ', '
}
ourOutput << i;
}
}
pros: don't change resulting string
cons: check on each iteration;
2nd approach:
ourOutput = ''<<'';
for (int i = 0; i< 10, i++) {
if (/*some condition goes here*/) {
ourOutput << i << ', ';
}
}
if (ourOutput.size() != 0) {
ourOutput.setLength(ourOutput.length() - 2);
}
pros: don't check each time
cons: modifying resulting string.
Please advise, which one to use or maybe there is some better way to do that?
p.s. code written in groovy, feel free to replace ''<<'' with new StringBuilder() and << with .append() so it became java-compilable.
There's an excellent library to aid you with this, Commons Lang StringUtils
StringUtils.join(C, ",");
where C can be either a Collection, Array, or Iterator.
The lang library of Apache Commons has a nice method for this:
StringUtils.join(java.util.Collection,char)
If this is groovy, why not just do:
String ourOutput = (0..9).join( ',' )
As it's Groovy code, a concise solution is to store each item in a List then join the List to create a comma-separated string, e.g.
List ourOutput = []
for (int i = 0; i < 10, i++) {
if (/*some condition goes here*/) {
ourOutput << i
}
}
String commaSeparated = ourOutput.join(',')
You can do this task in two step:
split String variable by one to one character (it means : test ==>> String{"t","e","s","t"})
join array reult in above step by Apache Commons Lang3
I write a utility method for this task:
public static String join(String src, String separator)
{
String[] array = src.split("\\.?");
String newString = StringUtils.join(array, separator);
String finalResult = newString.substring(1, newString.length());
System.out.println(finalResult);
return finalResult;
}
if you execute this method with two argument as TEST and , you will see following output in console:
T,E,S,T
I hope my answer useful for you.
You can use following method to add separator to any array.
Defining joinSeparator()
public static String joinSeparator(Object[] array, char separator) {
if (array == null) {
return null;
}
int startIndex = 0;
int endIndex = array.length;
int bufSize = (endIndex - startIndex);
if (bufSize <= 0) {
return null;
}
bufSize *= ((array[startIndex] == null ? 16 : array[startIndex]
.toString().length()) + 1);
StringBuffer buf = new StringBuffer(bufSize);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
Call joinSeparator() method
String[] array = {"sunil", "kumar", "sahoo"};
joinSeparator(array, ',');

Add spaces between the characters of a string in Java?

I just want to add a space between each character of a string. Can anyone help me figuring out how to do this?
E.g. given "JAYARAM", I need "J A Y A R A M" as the result.
Unless you want to loop through the string and do it "manually" you could solve it like this:
yourString.replace("", " ").trim()
This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.
ideone.com demonstration
An alternative solution using regular expressions:
yourString.replaceAll(".(?=.)", "$0 ")
Basically it says "Replace all characters (except the last one) with with the character itself followed by a space".
ideone.com demonstration
Documentation of...
String.replaceAll (including the $0 syntax)
The positive look ahead (i.e., the (?=.) syntax)
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i > 0) {
result.append(" ");
}
result.append(input.charAt(i));
}
System.out.println(result.toString());
Iterate over the characters of the String and while storing in a new array/string you can append one space before appending each character.
Something like this :
StringBuilder result = new StringBuilder();
for(int i = 0 ; i < str.length(); i++)
{
result = result.append(str.charAt(i));
if(i == str.length()-1)
break;
result = result.append(' ');
}
return (result.toString());
Blow up your String into array of chars, loop over the char array and create a new string by succeeding a char by a space.
Create a StringBuilder with the string and use one of its insert overloaded method:
StringBuilder sb = new StringBuilder("JAYARAM");
for (int i=1; i<sb.length(); i+=2)
sb.insert(i, ' ');
System.out.println(sb.toString());
The above prints:
J A Y A R A M
This would work for inserting any character any particular position in your String.
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
Then call it like this
String result = InsertSpaces.insertCharacterForEveryNDistance(1, "5434567845678965", ' ');
System.out.println(result);
I am creating a java method for this purpose with dynamic character
public String insertSpace(String myString,int indexno,char myChar){
myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
System.out.println(myString);
return myString;
}
This is the same problem as joining together an array with commas. This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:
String input = "Hello";
StringBuilder result = new StringBuilder();
if (input.length() > 0) {
result.append(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
result.append(" ");
result.append(input.charAt(i));
}
}
public static void main(String[] args) {
String name = "Harendra";
System.out.println(String.valueOf(name).replaceAll(".(?!$)", "$0 "));
System.out.println(String.valueOf(name).replaceAll(".", "$0 "));
}
This gives output as following use any of the above:
H a r e n d r a
H a r e n d r a
One can use streams with java 8:
String input = "JAYARAM";
input.toString().chars()
.mapToObj(c -> (char) c + " ")
.collect(Collectors.joining())
.trim();
// result: J A Y A R A M
A simple way can be to split the string on each character and join the parts using space as the delimiter.
Demo:
public class Main {
public static void main(String[] args) {
String s = "JAYARAM";
s = String.join(" ", s.split(""));
System.out.println(s);
}
}
Output:
J A Y A R A M
ONLINE DEMO
Create a char array from your string
Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
BOOM...done!!
If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.
Or creating a char array and converting it back to the string would yield the same result.
Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.
I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break)
and
\u00A0 (for spacing)
or alternatively
$#032

Categories

Resources