简体   繁体   English

在最后一次出现任何字符之前连接一个字符串

[英]Concatenate a string before the last occurrence of any character

I want to concatenate a string before the last occurrence of any character. 我想在最后一次出现任何字符之前连接一个字符串。

I want to do something like this: 我想做这样的事情:

addToString(lastIndexOf(separator), string);

where "ddToString" is a function that would add the "string" before the "lastIndexOf(separator)" 其中“ddToString”是一个在“lastIndexOf(separator)”之前添加“string”的函数

Any ideas? 有任何想法吗?

One way I thought of is making string = string + separator . 我想到的一种方法是使string = string + separator But, I can't figure out how to overload the concatenate function to concatenate after a particular index. 但是,我无法弄清楚如何在特定索引之后重载concatenate函数以进行连接。

You should look in Java's api at http://download.oracle.com/javase/7/docs/api/ and use the String Classes substring(int beginIndex)method after you find the index of your specified character so 您应该在http://download.oracle.com/javase/7/docs/api/上查看Java的api,并在找到指定字符的索引后使用String Classes substring(int beginIndex)方法

public String addToString(String source, char separator, String toBeInserted) {
        int index = source.lastIndexOf(separator); 
        if(index >= 0&& index<source.length())
    return source.substring(0, index) + toBeInserted + source.substring(index);
        else{throw indexOutOfBoundsException;}
}

Try this: 试试这个:

static String addToString(String source, int where, String toInsert) {
    return source.substring(0, where) + toInsert + source.substring(where);
}

You'll probably want to add some parameter checking (in case character isn't found, for instance). 您可能想要添加一些参数检查(例如,如果找不到字符)。

You need to use StringBuffer and method append(String) . 您需要使用StringBuffer和方法append(String) Java internally converts + between String s into a temporary StringBuffer , calls append(String) , then calls toString() and lets the GC free up allocated memory. Java的内部转换+之间的String s转换为临时StringBuffer ,调用append(String) ,然后调用toString()并让GC释放分配的内存。

The simple way is: 简单的方法是:

String addToString(String str, int pos, String ins) {
    return str.substring(0, pos) + ins + str.substring(pos);
}

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

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