How to Extract Numbers from a String and Get an Array of Ints

Extracting integers from a String into an Array

You can use a regular expression to extract numbers:

String s = "First number 10, Second number 25, Third number 123 ";
Matcher matcher = Pattern.compile("\\d+").matcher(s);

List<Integer> numbers = new ArrayList<>();
while (matcher.find()) {
numbers.add(Integer.valueOf(matcher.group()));
}

\d+ stands for any digit repeated one or more times.

If you loop over the output, you will get:

numbers.forEach(System.out::println);

// 10
// 25
// 123

Note: This solution does only work for Integer, but that is also your requirement.

How to extract numbers from a String into an array

First split the string. Then parse each element in String array to new array

String[] s=str.split("\\D+");
int[] intarray=new int[s.length];
for(int i=0;i<s.length;i++){
intarray[i]=Integer.parseInt(s[i]);
}

How to extract numbers from a string and get an array of ints?

Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}

... prints -2 and 12.


-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.

Extract integer from string and form an array

cin >> string will stop at whitespace, so let's use std::getline which will grab a whole line of input.

And regexs are certainly a way of doing this:

code

#include <iostream>
#include <cstring>
#include <regex>

int main() {

int number_array = {};
std::string user_input;

std::cout << "Enter your array range: ";
std::getline(std::cin, user_input);
std::cout << "You have entered: " + user_input << "\n";

std::smatch m;
std::regex r(R"(^(\d+) *- *(\d+)$)");
if (!regex_match(user_input, m, r)) {
std::cout << "Didn't match regex!\n";
return 1;
}

int start = std::stoi(m[1]);
int end = std::stoi(m[2]);

for (int i=start; i<=end; i++) {
std::cout << i << " ";
}
std::cout << "\n";

return 0;
}

output

> clang++-7 -pthread -std=c++17 -o main main.c
pp
> ./main
Enter your array range: 1 -- 4
You have entered: 1 -- 4
Didn't match regex!
exit status 1
> ./main
Enter your array range: 4 - 10
You have entered: 4 - 10
4 5 6 7 8 9 10

https://repl.it/repls/FunctionalGiantChapters

that being said

Since you're parsing something pretty simple, you could also just use:

fscanf("%d - %d", &start, &end) and ignore the regex idea all together.

Extract numbers from a string into an array in c#

This will get an array of strings:

ids.Substring(1, ids.Length - 2).Split(',')

How to extract numbers from string containing numbers+characters into an array in Ruby?

Try using String#scan, like this:

str.scan(/\d+/)
#=> ["123", "84", "3", "98"]

If you want integers instead of strings, just add map to it:

str.scan(/\d+/).map(&:to_i)
#=> [123, 84, 3, 98]

Extracting numbers from a string in java

Just get digits with the Regex:

String str = "3x^2";
String pattern = "(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
ArrayList<Integer> numbers = new ArrayList<>();

Find with Matcher all numbers and add them to the ArrayList. Don't forget to convert them to int, because m.group() returns the String.

while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}

And if your formula doesn't contain the second number, add there your desired default item.

if (numbers.size<2) {
numbers.add(1);
}

Finally print it out with:

for (int i: numbers) {
System.out.print(i + " ");
}

And the output for 3x^2 is 3 2.

And for the 8x it is 8 1.

Extract numbers from a String and save them to an array

Here's an easy way to do it, unfortunately it does not use CharacterView because that would complicate it greatly:

func readFile(){
// Make sure getting the path and reading the file succeeds
guard
let path = Bundle.main.path(forResource: "paragraph", ofType: "txt"),
let fileContents = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
else { return }

// split string into substrings that only contain numbers
let substrings = fileContents.components(separatedBy: CharacterSet.decimalDigits.inverted)

// flatMap performs action on each substring
// and only returns non-nil values,
// thus returns [Int]

let numbers = substrings.flatMap {
// convert each substring into an Int?
return Int($0)
}

print(numbers)
}

Because the initializer for Int takes a String there is no need to use CharacterView. Once the numbers in the text are split from their non-digits they can be converted directly from String to Int. To use CharacterView would be an unnecessary intermediate. You could, however, code your own version of Int init?(String) which uses CharacterView to build the value.



Related Topics



Leave a reply



Submit