VBScript 字符串替换为范围而不是字符串? [英] VBScript string replace with range instead of string?

查看:53
本文介绍了VBScript 字符串替换为范围而不是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Replace() 已经存在,但该函数将字符串作为参数.我需要范围.

Replace() already exists, but that function takes strings as parameters. I need range.

在我的字符串中有两个长度为 10 个字符的字符串".Greger 有 6 个字符和 4 个空格,另一个字符串有 10 个字符.

In my string there are two "strings" that are 10 characters long. Greger with 6 chars and 4 spaces and the other string with 10 characters.

"Greger    AASSDDFFGG"

我想将 "Greger " 替换为 "googlioa "

我正在寻找的基本上是这样的:

What i'm looking for is basically this:

Replace(MyString,1,10) = "googlioa  "

有什么办法可以实现吗?

Is there any way to achieve this?

推荐答案

如果要严格按位置替换,请使用 Left()、new 和 Mid() 的串联.让您开始:

If you want to replace strictly by position, use concatenation of Left(), new, and Mid(). To get you started:

>> Function replByPos(s, f, l, n)
>>   replByPos = Left(s, f-1) & n & Mid(s, f + l - 1)
>> End Function
>> s = "Greger    AASSDDFFGG"
>> r = replByPos(s, 1, 10, "googlioa ")
>> WScript.Echo s
>> WScript.Echo r
>>
Greger    AASSDDFFGG
googlioa  AASSDDFFGG
>>

进一步增强:

  1. 安全:f(rom) - 1 有风险 - 应该检查
  2. 填充新字符串 wrt l(ength)
  3. 也许您想在连接之前搜索 (Instr()) 以查找旧的 ("Greger ")
  1. safety: f(rom) - 1 is risky - should be checked
  2. padding of new string wrt l(ength)
  3. perhaps you want to search (Instr()) for old ("Greger ") before the concatenation

再三考虑(偷了邦德的填充物):

也许我应该将 10 解释为 to/till/upto 值而不是长度/宽度规范.所以看看是否

Maybe I should have interpeted the 10 as a to/till/upto value instead of a length/width specification. So see whether

Option Explicit

Function replByPos(src, from, till, ns)
  Dim w : w = till - from
  replByPos = Left(src, from - 1) & Left(ns & Space(w), w) & Mid(src, till)
End Function

Dim s  : s  = "Greger    AASSDDFFGG"
Dim ns : ns = "googlioa"

WScript.Echo s
WScript.Echo replByPos(s, 1, 10, ns)

s  = "Whatever Greger    AASSDDFFGG"
ns = "googlioa"

Dim p : p = Instr(s, "Greger")
WScript.Echo s
WScript.Echo replByPos(s, p, p + 10, ns)

输出:

cscript 22811896.vbs
Greger    AASSDDFFGG
googlioa  AASSDDFFGG
Whatever Greger    AASSDDFFGG
Whatever googlioa  AASSDDFFGG

更符合您的规格.

这篇关于VBScript 字符串替换为范围而不是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆