-5

i have a String and i want change it to Array next show only split words in one line. I have not idea how to do it my only idea is to do this like that :

public static void main(String[] args) {
    String ciag="Hello My name is Tomek, i am from Mars.";
    ciag=ciag.replaceAll(",", "").replaceAll(".", "");
    System.out.println(ciag);

but it is wrong too any advice's

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Hebel
  • 23
  • 3
  • 1
    [`replaceAll`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-) accepts a regex, `.` matches everything in your string. Use `replace` instead. – Maroun Jun 07 '16 at 12:29
  • 3
    People from Mars should already know that. – Maroun Jun 07 '16 at 12:30
  • Advise: read the javadoc for the functions you are calling **carefully**. Typically **everything** you ever need to know about them is already written down there. Yes, asking questions here is fun ... but reading javadoc is more efficient. And being downvoted for not doing prior research isn't real fun anyway I guess. – GhostCat Jun 07 '16 at 12:32
  • Related: http://stackoverflow.com/a/33444647/1393766 – Pshemo Jun 07 '16 at 12:35

2 Answers2

3

This will work.

String ciag="Hello My name is Tomek, i am from Mars.";
ciag=ciag.replace(",", "").replace(".", "");
System.out.println(ciag);
String[] arr = ciag.split("\\s+");

replaceAll() uses RegEx to replace and in RegEx . stands for any character. Use replace().

split() also takes a RegEx and \s+ matches one or more occurrences of a whitespace.

Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58
2
String ciag="Hello My name is Tomek, i am from Mars.";
String[] words = ciag.replaceAll("[,.]", "").split("\\s+");

Testing:

System.out.println(Arrays.asList(words).toString());

Output:

[Hello, My, name, is, Tomek, i, am, from, Mars]

Explanation:

[,.] Is a regular expression. The [] is a character class, meaning that the regex will match any character inside the brackets. So [,.] means match a comma or a full stop. Any match for this character class will be replaced with an empty String replaceAll("[,.]", ""), so as a result of this, all commas and full stops are removed.

After the replacing is completed, we then split the resulting String with another regular expression \\s+ which matches one or more whitespace. So split("\\s+") will split the String into words.

explv
  • 2,709
  • 10
  • 17