简体   繁体   English

如何在不使用split,substring或index的情况下剪切特定字符的字符串?

[英]How do you cut a string at a certain character, without using split, substring, or index?

for a school assignment, I have to cut the string off at a certain character. 对于学校作业,我必须切断某个字符的字符串。 It takes an email as input, ex: name@mail.ca, and it has to print everything before the @ sign. 它以电子邮件作为输入,例如:name@mail.ca,并且必须在@符号之前打印所有内容。 We are not allowed to use substring, index or split. 我们不允许使用子字符串,索引或拆分。 I've attached what i've tried so far. 我已经附上了到目前为止我已经尝试过的东西。

public static void main(String[] args) {
    getPrefix("name@email.ca");
}


public static String getPrefix(String email) {
    String prefix = "";
    for (int i = 0; i < email.length(); i++) {
        if (email.charAt(i) == '@') {
            break;

        }

        prefix += email.charAt(i);
    }
    return prefix;
}

if i set the input as name@email.ca it prints: ame@email.caame@email.caame@email.caame@email.ca 如果我将输入设置为name@email.ca,它将打印:ame @ email.caame @ email.caame @ email.caame @ email.ca

So right now it is only taking away the first character, when instead I need it to take away everything from the @ onwards. 所以现在它只是带走第一个字符,相反,我需要它带走@以后的所有字符。

Also,I have to return the value rather than just print it, so how would I do that outside the loop. 另外,我必须返回值而不是仅仅打印它,所以我将如何在循环外执行该操作。

Use StringBuilder to append each char of string before @ , If you can't use StringBuilder you can use String but i won't recommended to use string for this 使用StringBuilder@之前附加字符串的每个字符,如果不能使用StringBuilder ,则可以使用String但我不建议为此使用string

 public static String getPrefix(String email) {

       StringBuilder builder = new StringBuilder();    // or String str = "";

       for (int i = 0; i < email.length(); i++) {
            if (email.charAt(i) == '@') {
                break;

            }
            builder.append(email.charAt(i));      //or str+=email.charAt(i);
       }
      return builder.toString();                   //or return str;
   }

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

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