VBScript string replace with range instead of string?

前端 未结 2 692
无人及你
无人及你 2021-01-29 01:16

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

In my string there are two \"strings\" that are 10 characters long. Greger with 6

相关标签:
2条回答
  • 2021-01-29 01:52

    If they're always going to be 10 chars, just pad the names.

    strNameFind    = "Greger"
    strNameReplace = "googlioa"
    
    ' Pad the names...
    strNameFind    = Left(strNameFind    & Space(10), 10)
    strNameReplace = Left(strNameReplace & Space(10), 10)
    
    MyString = Replace(MyString, strNameFind, strNameReplace)
    

    Alternatively, if you don't want to determine the existing name, just pad your new name appropriately and add the remainder of your string:

    ' Pad the new name to fit in a 10-char column...
    strNameReplace = "googlioa"
    strNameReplace = Left(strNameReplace & Space(10), 10)
    
    ' Update the record...
    MyString = strNameReplace & Mid(MyString, 11)
    
    0 讨论(0)
  • 2021-01-29 02:10

    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
    >>
    

    Further enhancements:

    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

    On second thought (and stealing Bond's padding):

    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)
    

    output:

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

    matches your specs better.

    0 讨论(0)
提交回复
热议问题