【问题标题】:When should you start using string replace over sprintf?什么时候应该开始在 sprintf 上使用字符串替换?
【发布时间】:2011-12-20 17:07:18
【问题描述】:

首先,我可能以错误的方式使用 sprintf。

我正在制作一个将字符串作为配置的框架插件。字符串有一些东西需要换掉,例如,一个字符串将是一个路径模板:

[root]/[template_directory]/something/specific/[theme_name].htm

上面的例子非常具体,有很多变量要换掉。

为了减少变量,我一直这样做:

sprintf('%s/some/file/path/theme.htm',documentroot);

但是,我想知道 sprintf 是否可能更难以用于更多变量。

在第一个示例中,我应该对每个变量使用字符串替换,还是应该使用 sprintf?还是我严重使用 sprintf 错误?

非常感谢任何建议!

【问题讨论】:

  • 您使用的是 C++?您是否考虑过使用字符串流?
  • @Hurkyl 这不是特定于语言的;我正在用 PHP 编写代码,但 sprintf 和字符串替换有几种语言。
  • @Kyle:我误读了这个问题。 :(
  • 我认为这取决于您使用的语言。在 C 中使用 snprintf()/strncat(),在 C++ 中使用 std::string/std::stringstream,在 Java 和 php 中使用最好的。所以选择一种语言。

标签: java php c++ printf


【解决方案1】:

也许你可以在 std::string: 中使用替换:

请看这个例子: http://www.devx.com/getHelpOn/10MinuteSolution/16972/1954

std::string phrase = "[root]/[template_directory]/something/specific/[theme_name].htm";
std::string sought = "[root]";
std::string replacement = "newROOT";

phrase.replace(phrase.find(sought), 
               sought.size(), 
               replacement);

祝你好运!

【讨论】:

    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2014-10-27
    • 2014-06-16
    • 2011-05-16
    • 2014-06-10
    • 2023-04-02
    相关资源
    最近更新 更多