Java - 在字符串中查找并从右侧开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6973777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:06:07  来源:igfitidea点击:

Java - find in string and start from the right

java

提问by Steve

Maybe I am making this too complicated but I think I need to start reading a string from the right to find its position. Here is my sample:

也许我把它弄得太复杂了,但我想我需要从右边开始读取一个字符串来找到它的位置。这是我的示例:

10000000000000000101

In this string I need to find all the '1' and get the position that they are on. In this case it would be 1,3 and 19.

在这个字符串中,我需要找到所有的“1”并获得它们所在的位置。在这种情况下,它将是 1,3 和 19。

Is that an easy way to do this?

这是一个简单的方法来做到这一点吗?

Thank you all.

谢谢你们。

回答by mjisrawi

    String mystring = "10000000000000000101";
    for(int i=0; i < mystring.length(); i++){
        if(mystring.charAt(i) == '1'){
             int rightPosition = mystring.length() - i; 
             // do what ever you want with character and its position
        }
    }

回答by Jon Skeet

Given that you need to find allthe positions, I don't think you really need to find the positions from right to left - you can find their "normal" indexes, and just compute how many positions that would be from the right.

鉴于您需要找到所有位置,我认为您真的不需要从右到左找到位置 - 您可以找到它们的“正常”索引,然后计算从右侧开始的位置数。

So use indexOf(int, int)repeatedly, and subtract the returned index from the length of your string:

所以indexOf(int, int)重复使用,并从字符串的长度中减去返回的索引:

public static void showSetBits(String text)
{
    int lastPosition = -1;
    while ((lastPosition = text.indexOf('1', lastPosition + 1)) != -1)
    {
        System.out.println("Found set bit at position " + 
                           (text.length() - lastPosition));
    }
}

If you ever dowant to go from right to left, you can always use lastIndexOf.

如果您确实想从右向左移动,则始终可以使用lastIndexOf.

回答by Kal

Use java.lang.String#indexOfto find the index from the left.

用于java.lang.String#indexOf从左侧查找索引。

Then subtract from the length of the string.

然后从字符串的长度中减去。

    String abc = "10000000000000000101";
    int fromIndex = 0;
    int idx = 0;
    do {
        idx = abc.indexOf("1", fromIndex);
        if (idx == -1)
            break;
        System.out.println(abc.length() - idx);
        fromIndex = idx + 1;
    } while (idx != -1);
}

回答by DaMainBoss

One way would be to use the reversemethod in the StringBuilderclass. So first we reverse the string:

一种方法是在StringBuilder类中使用reverse方法。所以首先我们反转字符串:

//declare and initialise string
String str = "10000000000000000101";

//First we take an instance of the StringBuilder, then
//we append the original string to it and lastly we reverse it and get the string value.
String reversed = new StringBuilder().append(str).reverse().toString();

Now we have reversed the string all you just have to do is loop through the string and keep track of the index at which you encounter a 1. You can easily use an ArrayList. Each time you encounter a 1, you add the index to that list.

现在我们已经反转了字符串,您只需要循环遍历字符串并跟踪遇到1. 您可以轻松使用ArrayList。每次遇到 a 时1,都会将索引添加到该列表中。

So lets declare an ArrayList of generic type Integer first and then loop through the reversed string.

因此,让我们首先声明一个泛型类型 Integer 的 ArrayList,然后循环遍历反向字符串。

ArrayList<Integer> list = new ArrayList<Integer>();

//we loop through the string..

for(int i=0; i<reversed.length(); i++)
{
    if(reversed.charAt(i) == '1'){
         list.add(i);
    }
}

Now you have the list of indices so you can just print them out or do whatever you want with them. For a problem like yours, there are a few shorter ways to do this but I explained a more detailed and efficient way you could use to tackle such a problem if you do not have any idea what the original string looks like(say you just have a text file with millions of lines or whatever)

现在您有了索引列表,因此您可以将它们打印出来或对它们执行任何您想要的操作。对于像你这样的问题,有一些更短的方法可以做到这一点,但我解释了一种更详细、更有效的方法,如果你不知道原始字符串是什么样子的(假设你只是有一个包含数百万行或其他任何内容的文本文件)

回答by Shashwat

@mjisrawi Your code has some errors do check.

@mjisrawi 您的代码有一些错误请检查。

@steve ": String.charAt(char) is probably the easiest way to find out the number of instances, when used inside some control statement. Ofcourse you can get it done using other pre configured methods like indexOf()

@steve ": String.charAt(char) 可能是找出实例数量的最简单方法,当在一些控制语句中使用时。当然你可以使用其他预先配置的方法来完成它,比如 indexOf()

 String s = "100000000001000000101";

 int len = s.length();
 int count =0;

 while (len>0) {     
      if (s.charAt(len-1)=='1'){
          count ++;}                                     
     len --;
 }
     System.out.println("Number of 1 using String.charAt()" + " = " +count);

回答by Charles Goodwin

Probably the least verbose I can think of uses String split:

可能是我能想到的最简单的使用String split

String str = "10000000000000000101";
String[] bits = str.split("1");
System.out.println("Number of 1s: " + (bits.length-1));

Some people may consider this a bit of a hack or a bit inefficient, but it works fine for simple scenarios.

有些人可能会认为这有点黑客或有点低效,但它适用于简单的场景。

回答by fireshadow52

String searchString = "10000000000000000101";
for (int i = searchString.length; i >= 0; i--) {
    if (searchString.charAt(i).equals('1')) {
        System.out.println("" + i);
    }
}

This should do it

这应该做