如何在特定字符之前获取第一个空格的索引

时间:2016-11-28 10:36:07

标签: java string parsing

我的文件格式为

xbox one    gaming-consoles:xbox-one-games:gaming-controllers
xbox one games  xbox-one-games
xbox 360 games  xbox-360-games:gaming-consoles
xbox 360    gaming-consoles:xbox-360-games:gaming-controllers 

现在我想把线分成两部分。分裂的逻辑是它应该在字符':'

之前的第一个空格处完成

所以拆分的文字看起来应该是

xbox one             gaming-consoles:xbox-one-games:gaming-controllers
xbox one games       ox-one-games:gaming-controllers
xbox 360 games       xbox-360-games:gaming-consoles

依旧......

如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

您可以使用let messageBoxFrame = CGRect(x: 0, y: 0, width: 1024, height: BAND_HEIGHT) print(messageBoxFrame) let messageBox = UILabel(frame: messageBoxFrame) messageBox.textAlignment = .center messageBox.textColor = UIColor.white messageBox.backgroundColor = UIColor.blue messageBox.sizeToFit() print(messageBox.frame) 获取最后一个空格的字符串中的位置,然后使用lastIndexOf将字符串拆分为两个不同的变量。

substring

这给出了输出:

String s1 = "test string with lots of     spaces";
String s2 = s1.substring(0, s1.lastIndexOf(" "); //From the first character until the last space
String s3 = s1.substring(s1.lastIndexOf(" ")+1); //Index of last space+1 to end.
System.out.println(s1 + "\n" + s2 + "\n" + s3);

一个小问题是包含前半部分的字符串仍然会在字符串末尾包含空格,但如果需要test string with lots of spaces test string with lots of spaces 则可以很容易地调解。

答案 1 :(得分:0)

也许你可以使用正则表达式来提取每一行的第二部分。

(\\s[\\S]+)(?=:).+将预测(\\s[\\S]+)以检查其后跟:(\\s[\\S]+)选择以空格\s开头,后跟非空格字符[\S]+的组。

以下是示例代码:

import java.util.regex.*;

public class TestRegex {
    public static void main(String []args){
        String[] line = new String[] {
            "xbox one    gaming-consoles:xbox-one-games:gaming-controllers",
            "xbox one games  xbox-one-games",
            "xbox 360 games  xbox-360-games:gaming-consoles",
            "xbox 360    gaming-consoles:xbox-360-games:gaming-controllers "
        };

        String regex = "(\\s[\\S]+)(?=:).+";

        Pattern re = Pattern.compile(regex);

        for (String ln : line) {
            Matcher m = re.matcher(ln);
            if (m.find()) {
                System.out.println(m.group(0));
            }
        }
     }
}

答案 2 :(得分:0)

关于

  

分裂的逻辑是它应该在角色:

之前的第一个空格处完成

使用基于前瞻性的正面regex:

String s = "xbox one    gaming-consoles:xbox-one-games:gaming-controllers and more here";
String[] chunks = s.split(" ++(?=[^ :]*:)", 2);
System.out.println(Arrays.toString(chunks));
// => [xbox one, gaming-consoles:xbox-one-games:gaming-controllers and more here]

请参阅Java demo

split将产生一个(如果没有找到匹配)或2个块(因为传递了限制参数,2)。拆分将发生在1个或多个空格(请参阅" ++"),其后跟0 +字符而不是空格:(请参阅[^ :]*),然后是: