In my app, I get a string. For example:
"1 \n2 4 \n18 \n 3 20 12 \n 4\n23"
I want to get all the integers from the string like
1,2,4,18,3,20,12,4,23.
I can't use string.split. There are only 2 characters except numbers (new line character and space in my string).
Thanks in advance :)
Assuming that you only have integers (in range -2147483648 and 2147483647) in your text (and whitespaces) you can easily use Scanner
String input = "1 \n2 4 \n18 \n 3 20 12 \n 4\n23";
Scanner sc = new Scanner(input);
while(sc.hasNextInt())
System.out.println(sc.nextInt());
For numbers out of these range you can use nextLong or nextBigInteger. But if you are not interested in returning actual type and you are fine with having them as String you can simply use next.
You can use REGEX with \\d+.
public static void main(String[] args) {
String s = "1 \n2 4 \n18 \n 3 20 12 \n 4\n23";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group());
}
}
O/P :
1
2
4
18
3
20
12
4
23
Apart from the Pattern / Matcher reply above...
If only you want to use split, this will work:
String str = "1 \n2 4 \n18 \n 3 20 12 \n 4\n23";
StringBuffer bfr = new StringBuffer();
for (String splitStr: str.split("[\\n\\s]+")){
bfr.append("," + splitStr);
}
System.out.println(bfr.toString().substring(1));
}
or use tokenizer:
String str = "1 \n2 4 \n18 \n 3 20 12 \n 4\n23";
StringTokenizer strToken = new StringTokenizer(str, "[\n ]+");
StringBuffer bfr = new StringBuffer();
while (strToken.hasMoreElements()){
bfr.append("," + strToken.nextElement().toString());
}
System.out.println(bfr.toString().substring(1));
}
You can use StringTokenizer to do it on Android.
StringTokenizer tokens = new StringTokenizer(yourString, "\\n");
Related
I am trying to get the two player values from "line" String and insert them into player1 and player2, using regular expression.
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
String line;
String player1;
String player2;
while ((line = in.readLine()) != null) {
Scanner input = new Scanner(line);
input.useDelimiter("(.* [a-z] )|\\sby ");
if(line.toLowerCase().contains("kill")) {
kill += 1;
//i would like to set the player1 and player2 here
}
}
}
Fragment of my file(.txt):
13:37 Kill: 3 4 7: Oootsimo killed Dono da Bola by MOD_ROCKET_SPLASH
13:37 Item: 5 weapon_rocketlauncher
13:39 Item: 6 weapon_rocketlauncher
13:40 Item: 7 ammo_rockets
13:41 Item: 6 weapon_rocketlauncher
13:41 Item: 4 weapon_rocketlauncher
13:43 Kill: 2 5 6: Isgalamido killed Assasinu Credi by MOD_ROCKET
13:45 Kill: 1022 7 22: <world> killed Mal by MOD_TRIGGER_HURT
13:46 Kill: 4 3 7: Dono da Bola killed Oootsimo by MOD_ROCKET_SPLASH
13:46 Kill: 6 2 6: Zeh killed Isgalamido by MOD_ROCKET
I don't know all of your requirements, but try using Regexp:
#Test
public void test()
{
String string = "13:46 Kill: 6 2 6: Zeh killed Isgalamido by MOD_ROCKET";
String regexp = "\\d+:\\d+ .*?([A-Za-z0-9]+) killed ([A-Za-z0-9]+).*?";
String player1 = null;
String player2 = null;
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(string);
if (m.find())
{
player1 = m.group(1);
player2 = m.group(2);
}
assertEquals("Zeh", player1);
assertEquals("Isgalamido", player2);
}
Explanation:
\d+ - A digit, one or more times
.* - Any character, any number of times. the '?' means 'non greedy', so characters matching the following expression won't be overaken
([A-Za-z0-9]+) - character ranges inside the '[]', one or more times, captured
I'll edit my answer again once I can confirm this is what you meant
I have a string in java defined as below:
String numbers = null;
for (int i= 0; i < contactNumberList.size();i++)
{
numbers = contactNumberList.get(i) + "\n" + numbers;
}
where contactNumberList contains four items as : 9891, 3432, 5432, 9890.
So after the loop i have numbers string as:
9890\n5432\n3432\n9891\nnull
Then i passed the above string through following APIs.
String toUnicodeEncoded = StringEscapeUtils.escapeJava(numbers);
toUnicodeEncoded = StringEscapeUtils.escapeXml10(toUnicodeEncoded);
Now when i try to print the string toUnicodeEncoded character by character as below:
for (int i =0;i<toUnicodeEncoded.length();i++)
{
Logger.log("chat at "+i + " = "+(toUnicodeEncoded.charAt(i)));
}
It gives :
char at 0 = 9
char at 1 = 8
char at 2 = 9
char at 3 = 0
char at 4 = \
char at 5 = n
and so on .
My point is "\n" became two characters \ and n .
Now i wanted to split the string toUnicodeEncoded based on "\n" using the following APIs:
String lines[] = toUnicodeEncoded.split("\\n");
But its not able to split it because now "\n" has become \ and n. How do i split toUnicodeEncoded string by "\n" or new line character.
BAsically i want the output as :
9890
5432
3432
9891
null
i.e all four numbers . How do i do it.
When we split your string with \n it is giving expected output. But it is better to use System.getProperty("line.separator") instead of \n
String s="9890\n5432\n3432\n9891\nnull";
s = StringEscapeUtils.escapeJava(s);
s= StringEscapeUtils.escapeXml10(s);
for (String number:s.split("\n")) {
System.out.println(number);
}
result
9890
5432
3432
9891
null
use this, should do the trick
String.split("[\\r\\n]+")
Thanks everybody for replying. But i got it working using following approach:
String pattern = Pattern.quote("\\" + "n");
String lines[] = toUnicodeEncoded.split(pattern);
So I have a string which is from a text file, essentially the text file is just 5 lines which read:
x=1
y=15
z=128
topx=100
leftx=150
label= this is a test
I am able to get the split to work once which separates via the '=' sign, but when I try to split the string again by \n nothing works, I have tried using "\r?\n", line.Separator etc. but the string value always stays the same, basically the 5 lines without the characters before the = sign. How would I pull out the individual lines to assign variables to?
Here is the code I have, basically the println is to try and see if I can get the first value '1' to list separate from the rest of the lines.
public static void main(String[] a) {
15 draw d = new draw();
16 Read r = new Read();
17 String m = r.doRead("variables.txt");
18
19 String[] ss = new String[5];
20 ss = m.split("\n");
21
22 String[] kv= new String[5];
23 for (int i=0; i<ss.length; i++) {
24 kv = ss[i].split("=");
25 String eol = System.getProperty("line.seperator");
26 String test = kv[1];
27 String[] split = new String[5];
28 split = test.split("\n");
29
30
31
32
33 String first = split[0];
34 //String second = split[1];
35 //String third = split[2];
36 //String fourth = split[3];
37 //String fifth = split[4];
38 System.out.println(first);
39 }
When every line looks like
x=1 y=15 z=128 topx=100 leftx=150 label= this is a test
you should first split at a whitespace to get 5 parts (x=1, y=15, ...) and then at = to get the "key" and "value" part of each part.
check this out:
String s = "x=1\ny=15\nz=128\ntopx=100\nleftx=150\nlabel= this is a test";
String[] ss = s.split("\n");
System.err.println( Arrays.asList(ss[0].split("=")) );
First time here. I'm trying to write a program that takes a string input from the user and encode it using the replaceFirst method. All letters and symbols with the exception of "`" (Grave accent) encode and decode properly.
e.g. When I input
`12
I am supposed to get 28AABB as my encryption, but instead, it gives me BB8AA2
public class CryptoString {
public static void main(String[] args) throws IOException, ArrayIndexOutOfBoundsException {
String input = "";
input = JOptionPane.showInputDialog(null, "Enter the string to be encrypted");
JOptionPane.showMessageDialog(null, "The message " + input + " was encrypted to be "+ encrypt(input));
public static String encrypt (String s){
String encryptThis = s.toLowerCase();
String encryptThistemp = encryptThis;
int encryptThislength = encryptThis.length();
for (int i = 0; i < encryptThislength ; ++i){
String test = encryptThistemp.substring(i, i + 1);
//Took out all code with regard to all cases OTHER than "`" "1" and "2"
//All other cases would have followed the same format, except with a different string replacement argument.
if (test.equals("`")){
encryptThis = encryptThis.replaceFirst("`" , "28");
}
else if (test.equals("1")){
encryptThis = encryptThis.replaceFirst("1" , "AA");
}
else if (test.equals("2")){
encryptThis = encryptThis.replaceFirst("2" , "BB");
}
}
}
I've tried putting escape characters in front of the grave accent, however, it is still not encoding it properly.
Take a look at how your program works in each loop iteration:
i=0
encryptThis = '12 (I used ' instead of ` to easier write this post)
and now you replace ' with 28 so it will become 2812
i=1
we read character at position 1 and it is 1 so
we replace 1 with AA making 2812 -> 28AA2
i=2
we read character at position 2, it is 2 so
we replace first 2 with BB making 2812 -> BB8AA2
Try maybe using appendReplacement from Matcher class from java.util.regex package like
public static String encrypt(String s) {
Map<String, String> replacementMap = new HashMap<>();
replacementMap.put("`", "28");
replacementMap.put("1", "AA");
replacementMap.put("2", "BB");
Pattern p = Pattern.compile("[`12]"); //regex that will match ` or 1 or 2
Matcher m = p.matcher(s);
StringBuffer sb = new StringBuffer();
while (m.find()){//we found one of `, 1, 2
m.appendReplacement(sb, replacementMap.get(m.group()));
}
m.appendTail(sb);
return sb.toString();
}
encryptThistemp.substring(i, i + 1); The second parameter of substring is length, are you sure you want to be increasing i? because this would mean after the first iteration test would not be 1 character long. This could throw off your other cases which we cannot see!
I have a txt file formatted like:
Name 'Paul' 9-years old
How can I get from a "readline":
String the_name="Paul"
and
int the_age=9
in Java, discarding all the rest?
I have:
...
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
//put the name value in the_name
//put age value in the_age
}
...
Please suggest, thanks.
As you're using BufferedReader and everything is on the one line, you would have to split it to extract the data. Some additional formatting is then required to remove the quotes & extract the year part of age. No need for any fancy regex:
String[] strings = line.split(" ");
if (strings.length >= 3) {
String the_name= strings[1].replace("'", "");
String the_age = strings[2].substring(0, strings[2].indexOf("-"));
}
I notice you have this functionality in a while loop. For this to work, make sure that every line keeps the format:
text 'Name' digit-any other text
^^ ^^ ^
Important chars are
Spaces: min of 3 tokens needed for split array
Single quotes
- Hyphen character
use java.util.regex.Pattern:
Pattern pattern = Pattern.compile("Name '(.*)' (\d*)-years old");
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
String theName = matcher.group(1);
int theAge = Integer.parseInt(matcher.group(2));
}
}
You can use the String.substring, String.indexOf, String.lastIndexOf, and Integer.parseInt methods as follows:
String line = "Name 'Paul' 9-years old";
String theName = line.substring(line.indexOf("'") + 1, line.lastIndexOf("'"));
String ageStr = line.substring(line.lastIndexOf("' ") + 2, line.indexOf("-years"));
int theAge = Integer.parseInt(ageStr);
System.out.println(theName + " " + theAge);
Output:
Paul 9