-4

lets say Ive got string:

Java Android iOS

I need the output of it like this:

%java%
%android%
%ios%

or

%java%%android%%ios%

How can I do that?

Sorry, perhaps I didnt explain it okay.

String tok[]=input1.split(" ");
        for(String t:tok){
            System.out.println("%"+t.toLowerCase()+"%");
        }

that could be good answer but I forgot to mention that I need this saved, not only printed so best result would be as in example 2, so just adding %..% around every word

arienn
  • 230
  • 6
  • 18

5 Answers5

5

Try following:

String test="Java Android iOS";
        String tok[]=test.split("\\s+");
        for(String t:tok){
            System.out.println("%"+t.toLowerCase()+"%");
        }

Output :

%java%
%android%
%ios%

Basically all you need is to split the string from space character which can be done by split() and than append stuff as you like.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
4

You can try replaceAll() and split() like this :

public static void main(String[] args) {
    String s = "Java Android iOS";
    s = s.replaceAll("\\b(\\w+)\\b", "%$1%"); // capture and add
    String[] arr = s.split("\\s+");
    for (String str : arr) {
        System.out.println(str);
    }
}

O/P :

%Java%
%Android%
%iOS%
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • 1
    okay, that line input1 = input1.replaceAll("\\b(\\w+)\\b", "%$1%"); was what I was looking for, thanks – arienn Apr 21 '15 at 08:49
1
public String wrap(String input)
{
    String[] words = input.split(" "); //get array of words
    StringBuilder sb = new StreingBuilder(); //this is for perfomance
    for(String word : words) //affect each word in string
    {
        sb.append("%").append(word).append("%");
        //add %current_word% to result (if need, you may add space too
    }
    return sb.toString();
}
TEXHIK
  • 1,369
  • 1
  • 11
  • 34
1

Try this code:

String x = "I love java programming";
        String arrayX[] = x.split(" ");
        for(int i = 0; i<arrayX.length; i++){
            System.out.println("%"+arrayX[i].toLowerCase()+"%");
        }

output: %I% %love% %java% %programming%

Jemuel Elimanco
  • 416
  • 2
  • 4
  • 20
0
String example = "Java Android Ios";
String token[] = example.split("\\s+");

for(int i = 0; i < token.length; i++)  
{
     //%java%%android%%ios%
    System.out.print("%" + token[i].toLowerCase() + "%");
 //%java%
 //%android%
 //%ios%}
System.out.println("%" + token[i].toLowerCase() + "%");
Geen
  • 9
  • 4