-1

In Java if you want to split a String by a char or a String you can do that by the split method as follow:

String[] stringWords = myString.split(" ");

But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?

Here is a clear example:

String myString = "This is how the string should be";

String iWant = "This*is*how*the*string*should*be";

Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.

Here is an example:

String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");

myAlgorithmFucntion(stringWords);

Here is an example of how tha final string changes:

String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
Marco Micheli
  • 707
  • 3
  • 8
  • 26

4 Answers4

5

If you don't want to use replace or similar, you can use the Apache Commons StringUtils:

String iWant = StringUtils.join(stringWords, "*");

Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.

Community
  • 1
  • 1
xlm
  • 6,854
  • 14
  • 53
  • 55
  • 2
    I bet , StringUtils will internally also use for/while instructions which OP doesn't want. Basically OP is trying to ask something like Running a java program without JVM – Stunner Mar 04 '14 at 10:08
  • 2
    @Stunner I agree that `StringUtils` most likely does use iteration. I think his intention was to find out if there is an existing/convenient method in either the standard or popular Java libraries so he doesn't have to reinvent the wheel. – xlm Mar 04 '14 at 10:10
1

yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.

String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");


iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
RMachnik
  • 3,598
  • 1
  • 34
  • 51
-2

Try something like this as you don't want to use replace() function

char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Stunner
  • 961
  • 2
  • 19
  • 39
-2

Try looping the String array:

  String[] stringWords = myString.split(" ");
    String myString = "";
    for (String s : stringWords){
     myString = myString + "s" + "*";
    }

Just add the logic to deleting the last * of the String.

Using StringBuilder option:

String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
   myStringBuilder.append(s).append("*");
}
Averroes
  • 4,168
  • 6
  • 50
  • 63