更改“\”到“/”

发布于 2024-12-20 10:42:14 字数 202 浏览 5 评论 0 原文

我正在寻找一段简单的代码,它将使用 java 将字符串中的所有反斜杠更改为正斜杠。

我试过这个: word.replaceAll("\","/");

但这是行不通的。有人能快速解决这个问题吗?

谢谢

​ 我还注意到我的字符串操作几乎都不起作用。我尝试了像 toUpperCase() 这样的东西,但字符串没有发生任何变化?!?

I'm looking for a simple piece of code that will change all the backslashes in a string to forward slashes using java.

I tried this:
word.replaceAll("\","/");

but it will not work. Anyone have a quick fix for this?

Thanks

P.S.
I also just noticed that pretty much none of my string operations are working. I tried things like toUpperCase() and nothing happened to the string?!?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

永不分离 2024-12-27 10:42:14

replaceAll()错误使用的方法,因为它使用 正则表达式来匹配。

您想要更简单的 替换文字的 replace() 方法。试试这个:

word = word.replace("\\","/");

注意:

  1. 您必须用另一个反斜杠转义反斜杠,即 "\\" 是编码单个反斜杠字符串的方式 String
  2. are 不可变 - 字符串方法返回一个字符串及其结果...它们不会改变 字符串。这就是为什么您需要将其编码为 myString = myString.someMethod();

replaceAll() is the wrong method to use in this case, because it uses regular expressions to match.

You want the simpler replace() method that replaces literals. Try this:

word = word.replace("\\","/");

Notes:

  1. You have to escape the backslash with another backslash, ie "\\" is how you code a String that is a single backslash
  2. String are immutable - String methods return a new String with the result... they don't change the String. That's why you need to code it like myString = myString.someMethod();
我的痛♀有谁懂 2024-12-27 10:42:14

这些函数将返回一个新字符串,其中包含您尝试实现的更改,而不更改字符串本身。在 \ 情况下,您可能需要使用转义斜杠 ( \\ )

the functions will return a new string with the changes you are trying to implement not change the string itself. in the \ case you may need to use an escaped slash ( \\ )

私野 2024-12-27 10:42:14

在这种情况下,您需要使用:

word.replaceAll(("\\", "/");

toUpperCase() 返回一个字符串,它不会更改调用该方法的字符串。

http://docs.oracle.com/javase /1.5.0/docs/api/java/lang/String.html

In this case you would need to use:

word.replaceAll(("\\", "/");

toUpperCase() returns a string, it does not change the string calling the method.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

┈┾☆殇 2024-12-27 10:42:14

字符串不可变
他们永远无法改变。

您需要编写word = word.something()

Strings are immutable.
They can never change.

You need to write word = word.something().

故人如初 2024-12-27 10:42:14

你需要做的就是 word = word.replaceAll("\", "/");

您必须知道字符串无法更改。

这些方法的工作原理是迭代字符串的字符并用正斜杠替换所有反斜杠

all you need to do is word = word.replaceAll("\", "/");

you have to know that a string can't be changed.

those methods work by iterating over the characters of the string and replacing all the backlashes with forward slash

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文