www.91084.com

GVKun编程网logo

替代连续String.replace(替代连续剧苏朱)

19

在这篇文章中,我们将带领您了解替代连续String.replace的全貌,包括替代连续剧苏朱的相关情况。同时,我们还将为您介绍有关BashStringManipulationExamples–Leng

在这篇文章中,我们将带领您了解替代连续String.replace的全貌,包括替代连续剧苏朱的相关情况。同时,我们还将为您介绍有关Bash String Manipulation Examples – Length, Substring, Find and Replace--reference、Bash用另一个stringreplace空格和string的结尾、C++ string.replace的使用、C++ 使用 STL string 实现的 split,trim,replace - 修订的知识,以帮助您更好地理解这个主题。

本文目录一览:

替代连续String.replace(替代连续剧苏朱)

替代连续String.replace(替代连续剧苏朱)

我想替换String输入中的一些字符串:

string=string.replace("<h1>","<big><big><big><b>");string=string.replace("</h1>","</b></big></big></big>");string=string.replace("<h2>","<big><big>");string=string.replace("</h2>","</big></big>");string=string.replace("<h3>","<big>");string=string.replace("</h3>","</big>");string=string.replace("<h4>","<b>");string=string.replace("</h4>","</b>");string=string.replace("<h5>","<small><b>");string=string.replace("</h5>","</b><small>");string=string.replace("<h6>","<small>");string=string.replace("</h6>","</small>");

如您所见,这种方法不是最佳方法,因为每次我必须搜索要替换的部分时,等等,并且字符串是不可变的…而且输入很大,这意味着要考虑一些性能问题。

有没有更好的方法来减少此代码的复杂性?

答案1

小编典典

尽管StringBuilder.replace()与相比是一个巨大的改进String.replace(),但它 优化还差 很远

问题StringBuilder.replace()在于,如果替换的长度与可替换部分的长度不同(适用于我们的情况),则char可能必须分配更大的内部数组,并且必须复制内容,然后替换才会发生(这也涉及复制)。

想象一下:您有一个包含10.000个字符的文本。如果要将"XY"位置1(第2个字符)处的子字符串替换为"ABC",则实现必须重新分配char至少大于1
的缓冲区,必须将旧内容复制到新数组,并且必须复制9.997个字符(从位置3)右移1以适应"ABC"位置"XY",最后将的字符"ABC"复制到启动位置1。每次更换都必须这样做!太慢了

更快的解决方案:即时构建输出

我们可以 即时 构建输出:不包含可替换文本的部分可以简单地附加到输出中,并且如果我们找到可替换的片段,则可以替换而不是替换。从理论上讲,仅循环输入
一次 即可生成输出。听起来很简单,实现起来并不难。

实现方式:

我们将使用Map预加载的replaceable-replacement字符串的映射:

Map<String, String> map = new HashMap<>();map.put("<h1>", "<big><big><big><b>");map.put("</h1>", "</b></big></big></big>");map.put("<h2>", "<big><big>");map.put("</h2>", "</big></big>");map.put("<h3>", "<big>");map.put("</h3>", "</big>");map.put("<h4>", "<b>");map.put("</h4>", "</b>");map.put("<h5>", "<small><b>");map.put("</h5>", "</b></small>");map.put("<h6>", "<small>");map.put("</h6>", "</small>");

并使用它,这里是替换代码:( 代码后有更多解释)

public static String replaceTags(String src, Map<String, String> map) {    StringBuilder sb = new StringBuilder(src.length() + src.length() / 2);    for (int pos = 0;;) {        int ltIdx = src.indexOf(''<'', pos);        if (ltIdx < 0) {            // No more ''<'', we''re done:            sb.append(src, pos, src.length());            return sb.toString();        }        sb.append(src, pos, ltIdx); // Copy chars before ''<''        // Check if our hit is replaceable:        boolean mismatch = true;        for (Entry<String, String> e : map.entrySet()) {            String key = e.getKey();            if (src.regionMatches(ltIdx, key, 0, key.length())) {                // Match, append the replacement:                sb.append(e.getValue());                pos = ltIdx + key.length();                mismatch = false;                break;            }        }        if (mismatch) {            sb.append(''<'');            pos = ltIdx + 1;        }    }}

测试它:

String in = "Yo<h1>TITLE</h1><h3>Hi!</h3>Nice day.<h6>Hi back!</h6>End";System.out.println(in);System.out.println(replaceTags(in, map));

输出:( 包装以避免滚动条)

Yo<h1>TITLE</h1><h3>Hi!</h3>Nice day.<h6>Hi back!</h6>EndYo<big><big><big><b>TITLE</b></big></big></big><big>Hi!</big>Nice day.<small>Hi back!</small>End

该解决方案比使用正则表达式更快,因为它涉及很多开销,例如编译a
Pattern,创建Matcheretc等,并且regexp也更加通用。它还会在引擎盖下创建许多临时对象,这些对象在替换后会被丢弃。在这里,我只使用了一个StringBuilder(加号的char数组),并且代码String仅对输入进行一次迭代。同样,该解决方案比使用StringBuilder.replace()该答案顶部详细介绍的解决方案要快得多。

注释和解释

StringBuilder在这样的replaceTags()方法中初始化:

StringBuilder sb = new StringBuilder(src.length() + src.length() / 2);

因此,基本上,我以初始文件长度的150%的初始容量创建了它String。这是因为我们的替换项比可替换的文本长,因此,如果发生替换,则输出将明显长于输入项。赋予较大的初始容量StringBuilder将根本不会进行内部char[]重新分配(当然,所需的初始容量取决于可更换的替换对及其在输入中的出现频率/发生率,但这+
50%是一个不错的上限估计值)。

我还利用了所有可替换字符串都以''<''字符开头的事实,因此找到下一个潜在的可替换位置变得非常快:

int ltIdx = src.indexOf(''<'', pos);

这只是一个简单的循环和char内部的比较String,并且由于它总是从pos(而不是从输入的开头)开始搜索,因此,整个代码String仅对输入进行一次迭代。

最后要判断可替换String位置是否确实出现在可替换位置,我们使用该String.regionMatches()方法来检查可替换字符串,这也非常快,因为它所做的只是char在循环中比较值并在第一个不匹配字符处返回。

还有一个加号:

这个问题没有提及,但是我们的输入是一个HTML文档。HTML标记不区分大小写,这意味着输入内容可能包含<H1>而不是<h1>
对于此算法,这不是问题。类中的regionMatches()in
String有一个重载,它支持不区分大小写的比较:

boolean regionMatches(boolean ignoreCase, int toffset, String other,                          int ooffset, int len);

因此,如果我们想修改算法以查找和替换相同但使用不同字母大小写的输入标签,则只需修改以下一行:

if (src.regionMatches(true, ltIdx, key, 0, key.length())) {

使用此修改后的代码,可替换标签变得不区分大小写:

Yo<H1>TITLE</H1><h3>Hi!</h3>Nice day.<H6>Hi back!</H6>EndYo<big><big><big><b>TITLE</b></big></big></big><big>Hi!</big>Nice day.<small>Hi back!</small>End

Bash String Manipulation Examples – Length, Substring, Find and Replace--reference

Bash String Manipulation Examples – Length, Substring, Find and Replace--reference

In bash shell,when you use a dollar sign followed by a variable name,shell expands the variable with its value. This feature of shell is called parameter expansion.

But parameter expansion has numerous other forms which allow you to expand a parameter and modify the value or substitute other values in the expansion process. In this article,let us review how to use the parameter expansion concept for string manipulation operations.

This article is part of the on-going bash tutorial series. Refer to our earlier article on .

1. Identify String Length inside Bash Shell Script

${#string}

The above format is used to get the length of the given bash variable.

$ len.! /bin/var=<span>"<span>Welcome to the geekstuff<span>"

<span>echo<span> ${#var}

$ ./len.<span>sh
<span>24

To understand more about bash variables,read .

2. Extract a Substring from a Variable inside Bash Shell Script

Bash provides a way to extract a substring from a string. The following example expains how to parse n characters starting from a particular position.

${string:position}

Extract substring from $string at $position

${string:position:length}

Extract $length of characters substring from $string starting from $position. In the below example,first echo statement returns the substring starting from 15th position. Second echo statement returns the 4 characters starting from 15th position. Length must be the number greater than or equal to zero.

$ substr.! /bin/var=<span>"<span>Welcome to the geekstuff<span>"

<span>echo ${var:<span>15<span>}
<span>echo ${var:<span>15:<span>4<span>}

$ ./substr.<span>sh<span>
geekstuff
geek

Also,refer to our earlier article to understand more about .

3. Shortest Substring Match

Following syntax deletes the shortest match of $substring from front of $string

${string#substring}

Following syntax deletes the shortest match of $substring from back of $string

${string%substring}

Following sample shell script explains the above two shortest substring match concepts.

$ shortest.! /bin/filename=<span>"<span>bash.string.txt<span>"

<span>echo ${filename#<span>.}
<span>echo ${filename%.
<span>}

$ ./shortest.<span>sh<span>
After deletion of shortest match from front: <span>string<span>.txt
After deletion of shortest match from back: bash.<span>string

In the first echo statement substring ‘*.’ matches the characters and a dot,and # strips from the front of the string,so it strips the substring “bash.” from the variable called filename. In second echo statement substring ‘.*’ matches the substring starts with dot,and % strips from back of the string,so it deletes the substring ‘.txt’

4. Longest Substring Match

Following syntax deletes the longest match of $substring from front of $string

${string##substring}

Following syntax deletes the longest match of $substring from back of $string

${string%%substring}

Following sample shell script explains the above two longest substring match concepts.

$ longest.! /bin/filename=<span>"<span>bash.string.txt<span>"

<span>echo <span>"<span>After deletion of longest match from front:<span>" ${filename##<span>.}
<span>echo <span>"<span>After deletion of longest match from back:<span>" ${filename%%.
<span>}

$ ./longest.<span>sh<span>
After deletion of longest match from front: txt
After deletion of longest match from back: bash

In the above example,##*. strips longest match for ‘*.’ which matches “bash.string.” so after striping this,it prints the remaining txt. And %%.* strips the longest match for .* from back which matches “.string.txt”,after striping  it returns “bash”.

5. Find and Replace String Values inside Bash Shell Script

Replace only first match

${string/pattern/replacement}

It matches the pattern in the variable $string,and replace only the first match of the pattern with the replacement.

$ firstmatch.! /bin/filename=<span>"<span>bash.string.txt<span>"

<span>echo <span>"<span>After Replacement:<span>" ${filename/str*./<span>operations.}

$ ./firstmatch.<span>sh<span>
After Replacement: bash.operations.txt

Replace all the matches

${string//pattern/replacement}

It replaces all the matches of pattern with replacement.

$ allmatch.! /bin/filename=<span>"<span>Path of the bash is /bin/bash<span>"

<span>echo <span>"<span>After Replacement:<span>" ${filename<span>//<span>bash/sh}
<span>
$ ./allmatch.<span>sh<span>
After Replacement: Path of the <span>sh is /bin/<span>sh

Taking about find and replace,refer to our earlier articles –  and .

Replace beginning and end

${string/#pattern/replacement

Following Syntax replaces with the replacement string,only when the pattern matches beginning of the $string.

${string/%pattern/replacement

Following Syntax replaces with the replacement string,only when the pattern matches at the end of the given $string.

$ posmatch.! /bin/filename=<span>"<span>/root/admin/monitoring/process.sh<span>"

<span>echo <span>"<span>Replaced at the beginning:<span>" ${filename/#\/root/\/<span>tmp}
<span>echo <span>"<span>Replaced at the end<span>": ${filename/%.*/<span>.ksh}

$ ./posmatch.<span>sh<span>
Replaced at the beginning: /tmp/admin/monitoring/process.<span>sh<span>
Replaced at the end: /root/admin/monitoring/process.ksh

reference from:http://www.thegeekstuff.com/2010/07/bash-string-manipulation/

Bash用另一个stringreplace空格和string的结尾

Bash用另一个stringreplace空格和string的结尾

嗨,我希望有人可以帮助一个问题,

我需要从文本文件中获取特定的值,并将其转换为文档输出的整洁内容。 我有以下代码来获取值:

values=$(awk '/ParaMETER/ {getline ; getline; print ($(NF-6) )}' $array)

这给了我例如一个string: 9.00 5.00 9.00

现在我想将该string转换为: 9.0m,5.0m,9.0m 。 所以忽略第二个小数点并加上m,,。 值string的长度和值可能会有所不同,但始终有两位小数。

在Bash中自定义path完成

Bash:从文本文件VAR = VALUE格式中读取variables

perl -p -i -e用包含符号的文本replace行

Linux Bash Ftp自动映像上传

如何通过命令行列出昨天在目录中修改的文件?

如何快速做到这一点!?

基本上这是我需要分析的文本。 特别是我需要子集1的一个Z值和子集2的一个Z值:

MODEL ParaMETERS : Project : Report Dataset : xxx Number of subsets : 2 Total number : 4 Subset number : 1 Subset name : xxx_sub1 Number : 4 NR TYPE X(m) Y(m) Z(m) Volume Pressure CluNo Activ Group --- --------------------- ------ ------ ----- ------- -------- ----- ----- ------ 1 Type text 0.00 -10.40 9.00 2000.0 500.0 0 0 1 2 Type text 0.00 -9.60 9.00 1000.0 500.0 0 1 1 3 Type text 3.00 -10.40 9.00 1200.0 500.0 1 1 1 4 Type text 3.00 -9.60 9.00 800.0 500.0 1 1 1 Subset number : 2 Subset name : xxx_sub2 Number : 4 NR TYPE X(m) Y(m) Z(m) Volume Pressure CluNo Activ Group --- --------------------- ------ ------ ----- ------- -------- ----- ----- ------ 1 Type text 0.00 10.40 15.00 2000.0 500.0 0 0 1 2 Type text 0.00 9.60 15.00 1000.0 500.0 0 1 1 3 Type text 3.00 10.40 15.00 1200.0 500.0 1 1 1 4 Type text 3.00 9.60 15.00 800.0 500.0 1 1 1 Units : Coordinates : meter Volume : cubic cm Pressure : pascal

shell find -delete – 如何避免自己删除

:处理很多信号

控制台closures新鲜安装的Git Bash

Bash中的局部variables像Perl中一样?

有什么区别? 文件“和”./文件“在Linux bash shell?

awk -v OFS="," '{for(i=1;i<=NF;i++)$i=sprintf("%.1fm",$i)}7'

上述单线可能会帮助你。 检查测试:

kent$ echo "2000.44 234.88 9.00 5.00 9.00"|awk -v OFS=",$i)}7' 2000.4m,234.9m,9.0m,9.0m

使用bash和paste :

$ values="9.00 5.00 9.00" $ while IFS=,read val; do printf "%.1fmn" $val; done <<< $values | paste -sd,9.0m $ values="1.1000 2.4 3.400 42" $ while IFS=,1.1m,2.4m,3.4m,42.0m

C++ string.replace的使用

C++ string.replace的使用

//下面是一个检查一个字符串中是否有''.''的函数,该函数将找到的''.''转化为''_''。
inline void checkName(string& name)
{
std::string::size_type startpos = 0;
while (startpos!= std::string::npos)
{
    startpos = name.find(''.'');   //找到''.''的位置
    if( startpos != std::string::npos ) //std::string::npos表示没有找到该字符
    {
      name.replace(startpos,1,"_"); //实施替换,注意后面一定要用""引起来,表示字符串
    }
}
}

 

C++ 使用 STL string 实现的 split,trim,replace - 修订

C++ 使用 STL string 实现的 split,trim,replace - 修订

编辑器加载中...

使用 python 的时候默认 str 对字符串操作支持非常丰富,相信每个 C++ 程序员都自己写过 string 的 strim、split、replace,

写个小工具函数,留着用,以前偷懒,写了好几次,这次总结一下,贴出来。

 

#include <iostream>
#include <vector>
using namespace std;


namespace strtool
{
string trim(const string& str)
{
string
: :size_type pos = str.find_first_not_of('' '');
if (pos == string
: :npos)
{
return str
;
}
string::size_type pos2 = str.find_last_not_of('' '');
if (pos2 != string::npos)
{
return str.substr(pos, pos2 - pos + 1);
}
return str.substr(pos);
}

int split(const string& str, vector<string>& ret_, string sep = ",")
{
if (str.empty())
{
return 0;
}

string tmp;
string::size_type pos_begin = str.find_first_not_of(sep);
string::size_type comma_pos = 0;

while (pos_begin != string::npos)
{
comma_pos = str.find(sep, pos_begin);
if (comma_pos != string
: :npos)
{
tmp = str.substr(pos_begin, comma_pos - pos_begin)
;
pos_begin = comma_pos + sep.length();
}
else
{
tmp = str.substr(pos_begin);
pos_begin = comma_pos;
}

if (!tmp.empty())
{
ret_.push_back(tmp);
tmp.clear();
}
}
return 0;
}

string replace(const string& str, const string& src, const string& dest)
{
string ret;

string
: :size_type pos_begin = 0;
string
: :size_type pos = str.find(src);
while (pos != string
: :npos)
{
cout <<"replacexxx:" << pos_begin <<" " << pos <<"\n"
;
ret.append(str.data() + pos_begin, pos - pos_begin);
ret += dest;
pos_begin = pos + 1;
pos = str.find(src, pos_begin);
}
if (pos_begin < str.length())
{
ret.append(str.begin() + pos_begin, str.end());
}
return ret;
}

}




int main(int argc, char* argv[])
{
cout << strtool
: :trim(" nihao ") <<"\n";

vector<string> vt;
strtool
: :split(",o h,,,nice,,,,,,,", vt);
for (size_t i = 0; i < vt.size(); ++ i)
{
cout <<"out
: " << vt[i] <<"\n";
}

string ret = strtool::replace("xxAxxxAxxAxx", "A", "B");
cout <<"replace:" << ret <<"\n";
return 0;
}

原文链接: http://www.cnblogs.com/zhiranok/archive/2011/12/08/stl_string_trim_split_replace.html

我们今天的关于替代连续String.replace替代连续剧苏朱的分享已经告一段落,感谢您的关注,如果您想了解更多关于Bash String Manipulation Examples – Length, Substring, Find and Replace--reference、Bash用另一个stringreplace空格和string的结尾、C++ string.replace的使用、C++ 使用 STL string 实现的 split,trim,replace - 修订的相关信息,请在本站查询。

本文标签: