0

I need to remove the text after a space in a string using Java.

Input:

0 21343434
2 2323
6 232312


Output:

0
2
6

Anyone know how to do this? Just need to edit the string to remove everything after the space? Thanks!

Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
user2559299
  • 73
  • 1
  • 2
  • 5

6 Answers6

5

Use a regular expression

String result = "0 21343434".replaceAll(" .+$", "");

5
String string=  "0 21343434";
int spacePos = string.indexOf(" ");
if (spacePos > 0) {
   String youString= string.substring(0, spacePos - 1);
}
Dinup Kandel
  • 2,457
  • 4
  • 21
  • 38
0

Parse the string character by character with a for loop and search for a null then save the first character to a string and output it.

If you are newer to programming I'd refer you to this question and you may be able to use it to start moving in the right direction of your question

Remove "empty" character from String

Community
  • 1
  • 1
gcalex5
  • 1,091
  • 2
  • 13
  • 23
0

If you need to save the output in a file, you can read the input line by line and in each line just read the first character then save it to another file. At the end remove the first file and change the name of second file to the first file.

smo
  • 167
  • 7
0

Try this,

String str =  "0 21343434";
String[] vals = str.split(" ");
if (vals.length > 1)
    String value = vals[0];
Netch
  • 4,171
  • 1
  • 19
  • 31
Michael Shrestha
  • 2,547
  • 19
  • 30
0

Really simple. Make use of the indexOf method, substring method, and the ? operator to handle your base case (no spaces) and future cases (1 or more spaces).

String str = "hello world";
int firstSpace = (str.indexOf(" ") >= 0) ? str.indexOf(" ") : str.length()-1;
return str.substring(0,firstSpace);

This handles the case of there being no spaces as well. If there is no whitespace at all, the ? operation will return the value at the end of the string. Which in turn will output the whole string itself. Below are some examples:

Input:

0 21343434
2 2323
6232312

Output:

0
2
6232312