简体   繁体   English

如何告诉Java在字符串中的某个字符处停止循环?

[英]How do I tell java to stop the loop at a certain character in a string?

So if i have a method where a string is entered and has a hyphen. 因此,如果我有一个输入字符串并带有连字符的方法。 like "cool*boy" if i want java to make a new string that starts out at the end of that string and prints each letter backward and continues until it reaches the asterisk and then goes forward and prints all the letters after the asterisk again so in the cool*boy example it's "yobboy" or high*school would be "loohcsschool" ... how would I do this. 像“ cool * boy”一样,如果我想让java创建一个新字符串,该字符串从该字符串的末尾开始,并向后打印每个字母,一直到到达星号,然后继续前进,并在星号之后再次打印所有字母,所以在cool * boy例子中,“ yobboy”或高中学校将是“ loohcsschool” ...我将如何做。 Thank you. 谢谢。

to JUST get everything up to the asterisk sign (which isn't working) I put, 只需使所有内容都达到我所输入的星号(不起作用),

int i;
String newStr = "";
for(i=s.length()-1; i >= s.charAt('*'); i--)
     newStr = newStr + s.charAt(i);

I'm guessing you're not allowed to make that condition in the for loop. 我猜你不允许在for循环中做那个条件。 But I just don't get how you would do it. 但我只是不知道你会怎么做。 Please help thanks! 请帮忙谢谢!

将条件更改为

s.charAt(i) != '*'

The simplest way to do this would be to use a substring instead of a loop. 最简单的方法是使用子字符串而不是循环。

String forward = s.substring(s.indexOf('*')+1);
String reverse = new StringBuilder(forward).reverse().toString();
return reverse+forward;

not tested codes: 未经测试的代码:

String s = "high*school";

    String newString = "";
    String[] arr = s.split("[*]");
    if (arr.length == 2) {
        newString = new StringBuilder(arr[1]).reverse().toString() + arr[1];
    }else{
       ... if the string has no (or more than one) "*"...
        handle it if it is reqired.
     }

Don't reinvent the wheel. 不要重新发明轮子。 Apache Commons StringUtils library: Apache Commons StringUtils库:

substringBefore(String str, String separator)

substringAfter(String str,  String separator)

reverse(String str)

Link: http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/index.html 链接: http//commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/index.html

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

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