本文整理了Java中java.lang.String.replace()
方法的一些代码示例,展示了String.replace()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。String.replace()
方法的具体详情如下:
包路径:java.lang.String
类名称:String
方法名:replace
[英]Returns a new string resulting from replacing all occurrences of oldChar
in this string with newChar
.
If the character oldChar
does not occur in the character sequence represented by this String
object, then a reference to this String
object is returned. Otherwise, a new String
object is created that represents a character sequence identical to the character sequence represented by this String
object, except that every occurrence of oldChar
is replaced by an occurrence of newChar
.
Examples:
"mesquite in your cellar".replace('e', 'o')
returns "mosquito in your collar"
"the war of baronets".replace('r', 'y')
returns "the way of bayonets"
"sparring with a purple porpoise".replace('p', 't')
returns "starring with a turtle tortoise"
"JonL".replace('q', 'x') returns "JonL" (no change)
[中]返回将此字符串中所有出现的oldChar
替换为newChar
后生成的新字符串。
如果字符oldChar
未出现在此String
对象表示的字符序列中,则返回对该String
对象的引用。否则,将创建一个新的String
对象,该对象表示与此String
对象表示的字符序列相同的字符序列,但oldChar
的每一次出现都被newChar
替换。
示例:
"mesquite in your cellar".replace('e', 'o')
returns "mosquito in your collar"
"the war of baronets".replace('r', 'y')
returns "the way of bayonets"
"sparring with a purple porpoise".replace('p', 't')
returns "starring with a turtle tortoise"
"JonL".replace('q', 'x') returns "JonL" (no change)
代码示例来源:origin: spring-projects/spring-framework
/**
* Returns the internal name of the given class. The internal name of a class is its fully
* qualified name, as returned by Class.getName(), where '.' are replaced by '/'.
*
* @param clazz an object or array class.
* @return the internal name of the given class.
*/
public static String getInternalName(final Class<?> clazz) {
return clazz.getName().replace('.', '/');
}
代码示例来源:origin: google/guava
private void assertWithTemplate(String template, Item<T> item, Item<T> other, boolean condition) {
if (!condition) {
throw new AssertionFailedError(
template
.replace("$RELATIONSHIP", relationshipName)
.replace("$HASH", hashName)
.replace("$ITEM", itemReporter.reportItem(item))
.replace("$OTHER", itemReporter.reportItem(other)));
}
}
代码示例来源:origin: stackoverflow.com
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
代码示例来源:origin: google/guava
@VisibleForTesting
static String getClassName(String filename) {
int classNameEnd = filename.length() - CLASS_FILE_NAME_EXTENSION.length();
return filename.substring(0, classNameEnd).replace('/', '.');
}
代码示例来源:origin: stackoverflow.com
private static String getSubmittedFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
代码示例来源:origin: google/guava
@Override
String convert(CaseFormat format, String s) {
if (format == LOWER_UNDERSCORE) {
return s.replace('-', '_');
}
if (format == UPPER_UNDERSCORE) {
return Ascii.toUpperCase(s.replace('-', '_'));
}
return super.convert(format, s);
}
},
代码示例来源:origin: spring-projects/spring-framework
/**
* Constructs a new {@link ClassReader} object.
*
* @param className the fully qualified name of the class to be read. The ClassFile structure is
* retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}.
* @throws IOException if an exception occurs during reading.
*/
public ClassReader(final String className) throws IOException {
this(
readStream(
ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + ".class"), true));
}
代码示例来源:origin: spring-projects/spring-framework
/**
* Open an InputStream for the specified class.
* <p>The default implementation loads a standard class file through
* the parent ClassLoader's {@code getResourceAsStream} method.
* @param name the name of the class
* @return the InputStream containing the byte code for the specified class
*/
@Nullable
protected InputStream openStreamForClass(String name) {
String internalName = name.replace('.', '/') + CLASS_FILE_SUFFIX;
return getParent().getResourceAsStream(internalName);
}
代码示例来源:origin: spring-projects/spring-framework
protected byte[] transform(String className, byte[] classfileBuffer, CodeSource codeSource, ClassLoader classLoader)
throws Exception {
// NB: WebSphere passes className as "." without class while the transformer expects a VM "/" format
byte[] result = this.transformer.transform(classLoader, className.replace('.', '/'), null, null, classfileBuffer);
return (result != null ? result : classfileBuffer);
}
代码示例来源:origin: square/okhttp
private Request buildRequest(String hostname, int type) {
Request.Builder requestBuilder = new Request.Builder().header("Accept", DNS_MESSAGE.toString());
ByteString query = DnsRecordCodec.encodeQuery(hostname, type);
if (post) {
requestBuilder = requestBuilder.url(url).post(RequestBody.create(DNS_MESSAGE, query));
} else {
String encoded = query.base64Url().replace("=", "");
HttpUrl requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build();
requestBuilder = requestBuilder.url(requestUrl);
}
return requestBuilder.build();
}
代码示例来源:origin: google/guava
@Override
String convert(CaseFormat format, String s) {
if (format == LOWER_HYPHEN) {
return s.replace('_', '-');
}
if (format == UPPER_UNDERSCORE) {
return Ascii.toUpperCase(s);
}
return super.convert(format, s);
}
},
代码示例来源:origin: spring-projects/spring-framework
@Override
public void generateCode(MethodVisitor mv, CodeFlow cf) {
Method method = this.method;
Assert.state(method != null, "No method handle");
String classDesc = method.getDeclaringClass().getName().replace('.', '/');
generateCodeForArguments(mv, cf, method, this.children);
mv.visitMethodInsn(INVOKESTATIC, classDesc, method.getName(),
CodeFlow.createSignatureDescriptor(method), false);
cf.pushDescriptor(this.exitTypeDescriptor);
}
代码示例来源:origin: ReactiveX/RxJava
File directoryOf(String baseClassName) throws Exception {
File f = MaybeNo2Dot0Since.findSource("Flowable");
if (f == null) {
return null;
}
String parent = f.getParentFile().getAbsolutePath().replace('\\', '/');
if (!parent.endsWith("/")) {
parent += "/";
}
parent += "internal/operators/" + baseClassName.toLowerCase() + "/";
return new File(parent);
}
代码示例来源:origin: google/guava
private static ResourceInfo resourceInfo(Class<?> cls) {
String resource = cls.getName().replace('.', '/') + ".class";
ClassLoader loader = cls.getClassLoader();
return ResourceInfo.of(resource, loader);
}
代码示例来源:origin: google/guava
@Override
String convert(CaseFormat format, String s) {
if (format == LOWER_HYPHEN) {
return Ascii.toLowerCase(s.replace('_', '-'));
}
if (format == LOWER_UNDERSCORE) {
return Ascii.toLowerCase(s);
}
return super.convert(format, s);
}
};
代码示例来源:origin: spring-projects/spring-framework
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
String beanName = super.generateBeanName(definition, registry);
return beanName.replace("Impl", "");
}
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void splitSqlScriptDelimitedWithNewLineButDefaultDelimiterSpecified() {
String statement1 = "do something";
String statement2 = "do something else";
char delim = '\n';
String script = statement1 + delim + statement2 + delim;
List<String> statements = new ArrayList<>();
splitSqlScript(script, DEFAULT_STATEMENT_SEPARATOR, statements);
assertEquals("wrong number of statements", 1, statements.size());
assertEquals("script should have been 'stripped' but not actually 'split'", script.replace('\n', ' '),
statements.get(0));
}
代码示例来源:origin: spring-projects/spring-framework
@Test // SPR-12624
public void checkRelativeLocation() throws Exception {
String locationUrl= new UrlResource(getClass().getResource("./test/")).getURL().toExternalForm();
Resource location = new UrlResource(locationUrl.replace("/springframework","/../org/springframework"));
List<Resource> locations = singletonList(location);
assertNotNull(this.resolver.resolveResource(null, "main.css", locations, null).block(TIMEOUT));
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void checkRelativeLocation() throws Exception {
String locationUrl= new UrlResource(getClass().getResource("./test/")).getURL().toExternalForm();
Resource location = new UrlResource(locationUrl.replace("/springframework","/../org/springframework"));
assertNotNull(this.resolver.resolveResource(null, "main.css", Collections.singletonList(location), null));
}
代码示例来源:origin: spring-projects/spring-framework
@Test
public void renderWithPrettyPrint() throws Exception {
ModelMap model = new ModelMap("foo", new TestBeanSimple());
view.setPrettyPrint(true);
view.render(model, request, response);
String result = response.getContentAsString().replace("\r\n", "\n");
assertTrue("Pretty printing not applied:\n" + result, result.startsWith("{\n \"foo\" : {\n "));
validateResult();
}
内容来源于网络,如有侵权,请联系作者删除!