简体   繁体   English

检查字符串中的数字

[英]Checking numbers in a string

Notice: I know that there are tons of ways to make this simpler, but it is not allowed. 注意:我知道有很多方法可以简化此过程,但不允许这样做。 I am bounded to plain, basic java, loops and hand written methods. 我受限于普通的基本Java,循环和手写方法。 Even arrays are not allowed.Regex as well. 甚至数组也不允许使用。

Task is to check for numbers in each word of a sentence,find the word with the greatest number which is at the same time POWER OF 3. I did everything here and it works fine until I enter something like this. 任务是检查句子中每个单词的数字,找到最大数字的单词,同时最大功率为3。我在这里做了所有操作,直到我输入类似的内容,它都可以正常工作。

asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125

I receive output 64 instead of 125, because it stops checking when it reaches first number WHICH IS NOT POWER OF 3. 我收到的输出是64,而不是125,因为它在到达第一个不是幂数3的数字时停止检查。

How can I continue the iteration till the end of my sentence and avoid stopping when I reach non power of 3 number ,how to modify this code to achieve that ? 我如何才能继续迭代直到句子的结尾并避免在达到3的非幂次时停止,如何修改此代码以实现这一目标?

Edit: But if I enter more than one word after the one that FAILS THE CONDITION, it will work just fine. 编辑:但是,如果我在失败的单词后输入多个单词,它将正常工作。

for instance: 例如:

asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdash216 asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125 asdash216

Here is my code: 这是我的代码:

public class Nine {

static int num(String s) { // method to change string to int
    int b = 0;
    int o = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        char bi = s.charAt(i);
        b += (bi - '0') * (int) Math.pow(10, o);
        o++;

    }

    return b;
}

static boolean thirdPow(int a) {
    boolean ntrec = false;
    if (Math.cbrt(a) % 1 == 0)
        ntrec = true;
    return ntrec;

}



static int max(int a, int b) {
    int max= 0;
    if (a > b)
        max= a;
    else
        max= b;
    System.out.print(max);
    return max;
}

static String search(String r) {
    String current= ""; // 23aa64
    String currentA= "";
    String br = ""; // smjestamo nas broj iz rijeci 23
    int bb = 0; // nas pretvoreni string u broj
    int p = 0;

    for (int i = 0; i < r.length(); i++) {

        current+= r.charAt(i);
        if (r.charAt(i) == ' ') { 
            for (int j = 0; j < current.length(); j++) {
                while ((int) current.charAt(j) > 47 && (int) current.charAt(j) < 58) {
                    br += current.charAt(j); 
                    j++;
                }
                bb = num(br);
                System.out.println("Third pow" + thirdPow(bb));

                if (thirdPow(bb)) {
                    p = max(p, bb);

                }

                br = "";

            }

            current= "";

        }

    }

    String pp = "" + p;
    String finalRes= "";
    for (int u = 0; u < r.length(); u++) {
        currentA+= r.charAt(u);
        if (r.charAt(u) == ' ') {
            if (currentA.contains(pp))
                finalRes+= currentA;
            currentA= "";
        }
    }
    System.out.println(p);
    return finalRes;

}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter sentence: ");
    String r = scan.nextLine();

    System.out.println("Our string is : " + search(r));

}
  }

I am assuming that each word is separated by an empty space and containing non-Integers. 我假设每个单词都由一个空格隔开并且包含非整数。

Usage of regular expressions will certainly reduce the code complexity, Let's try this code: - 正则表达式的使用肯定会降低代码的复杂性,让我们尝试以下代码:-

String input = "asdas8 dasjkj27 asdjkj64 asdjk333 asdjkj125";

String[] extractWords = r.split(" ");        //extracting each words

int[] numbers = new int[extractWords.length]; // creating an Integer array to store numbers from each word

int i=0;

for(String s : extractWords) {
        numbers[i++] = Integer.parseInt(s.replaceAll("\\D+", "")); // extracting numbers
}

Now, the "numbers" array will contain [8, 27, 64, 333, 125] 现在,“数字”数组将包含[8、27、64、333、125]

You can use your logic to find a maximum among them. 您可以使用自己的逻辑在其中找到最大值。 Hope this helps. 希望这可以帮助。

Brother use 兄弟用

*string.split(" ");*

to form an array of strings and then iterate through the array and parse the numbers using regex 形成一个字符串数组,然后遍历该数组并使用正则表达式解析数字

^[0-9]

or 要么

\d+

and then find the biggest number from the array as simple as that. 然后从数组中找到最大的数字就这么简单。 Brother proceeds step by step then your code will run faster. Brother会逐步进行操作,然后您的代码将运行得更快。

You can just do what I am doing. 你可以做我正在做的事。 First split the sentence to chunks of words. 首先将句子拆分为单词块。 I am doing it based on spaces, hence the in.split("\\\\s+") . 我这样做是基于空格,因此是in.split("\\\\s+") Then find the numbers from these words. 然后从这些单词中找到数字。 On these numbers check for the highest number only if it is a power of 3. 在这些数字上,仅当其为3的幂时才检查最高数字。

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean isPowOfThree(int num)
{
    int temp = (int)Math.pow(num, 1f/3);
    return (Math.pow(temp, 3) == num);
}

public static void main (String[] args) throws java.lang.Exception
{
    Scanner sc = new Scanner(System.in);
    String in = sc.nextLine();
    String[] words = in.split("\\s+");
    String maxWord = ""; //init default word
    int maxNum = -1; //init default num

    for(String word : words)
    {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher(word);
        while (m.find()) 
        {
          String num = m.group();
          if(isPowOfThree(Integer.parseInt(num)))
          {
            if(Integer.parseInt(num) > maxNum)
            {
                maxNum = Integer.parseInt(num);
                maxWord = word;
            }
          }
        }
    }

    if(maxNum > -1)
    {
        System.out.println("Word is : " + maxWord);
    }
    else
    {
        System.out.println("No word of power 3");
    }

}
}

The problem can be solved using \\\\d+ regular expression with Matcher and Pattern API in Java. 使用\\\\d+正则表达式以及Java中的Matcher和Pattern API可以解决此问题。

package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String i = "asdas8 dasjkj278 asdjkj64 asdjk333 asdjkj125";
        Matcher matcher = Pattern.compile("\\d+").matcher(i);

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

        Collections.sort(numbers);
        Collections.reverse(numbers);

        Integer power3 = 0;

        for (Integer n : numbers) {
            if (isPowOfThree(n)) {
                power3 = n;
                break;
            }
        }
        System.out.println(power3);
    }

    static boolean isPowOfThree(int num) {
        int temp = (int)Math.pow(num, 1f/3);
        return (Math.pow(temp, 3) == num);
    }
}

Upon using \\\\d+ regular expression we get all the digits in the given string for every iteration of while(matcher.find()) . 使用\\\\d+正则表达式后,对于while(matcher.find())每次迭代,我们将获得给定字符串中的所有数字。 Once we collect all the numbers in the given string, we need to reverse sort the collection. 一旦我们收集了给定字符串中的所有数字,就需要对集合进行反向排序。 If we iterate over this collection, the first number that we find is the largest number which is a power of 3, since the collection is already sorted in descending order. 如果我们对该集合进行迭代,则发现的第一个数字是最大的数字(是3的幂),因为该集合已按降序排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM