+ 2
Hi, How do I add this sign - between a string? Please see my code below
public class Program { public static void main(String[] args) { String input = "Team Delta Team Echo"; String output = input.replaceAll(".(\\s)", "$0-"); System.out.println(output); // output is Team -Delta -Team -Echo // but I want Team Delta - Team Echo } }
7 Answers
+ 7
[Edit] Wait, thought you wanted "Team-Delta Team-Echo" ^^
Need some more minutes.
String s = "Team Delta Team Echo";
// split by the word Team but keep it (regex)
String[] arr = s.split("(?=Team)");
for(String str : arr) {
// replace first space by dash (regex)
str=str.replaceFirst("\\s+", "-");
System.out.println(str);
}
+ 6
Something like that:
String s = "Team Delta Team Echo";
String[] arr = s.split("(?=Team)");
String t = "";
for(int i =0; i < arr.length; i++) {
if (i<arr.length-1)
t += arr[i] + "- ";
else
t += arr[i];
}
System.out.print(t);
+ 6
Wait... here's the link... copy/paste is not good ;)
https://code.sololearn.com/cYj6v3iLrJMY/?ref=app
+ 6
I think I didn't quite understand what result you want yet, but... I'd split everything up by the word team like I did in the example. Then trim the spaces and re-add them where you want them + the dashes. Maybe you experienced the problems because of the spaces, then trim() will help you.
Sorry, I've got a problem with my notification list atm, so I won't see your replies until the bug is fixed :(
+ 1
thanks much appreciated. Your last code you wrote returned 3 errors.
+ 1
Thank you so much Tashi. My question was based on the code below. As you can see when I call the array index I don't get the exact info I want. what I want is when I call an element with index number get something like Team Alfa - Team Bravo and so on. When I call some elements I get like Team Bravo Team Charlie or some indexes just return white space (empty). Is there a way I can get around that?
https://code.sololearn.com/cTpU5Q8rQqLl/?ref=app
0
the code I'm building will extract data of teams from a website using a for each loop, then I will receive the teams like Team A - Team B(the format on a website uses a - sign to separate teams) Team B - Team C and so on. instead of printing the result I will use them within a code, so I need to add them to an array or ArrayList or something. I will use a code to compare with some conditions then add a team which meet the condition. the teams are dynamic so they will not always be Team A - Team B .