Jens Bergvall
Jens Bergvall

Reputation: 1627

VBScript string replace with range instead of string?

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 chars and 4 spaces and the other string with 10 characters.

"Greger    AASSDDFFGG"

I want to replace "Greger " with "googlioa "

What i'm looking for is basically this:

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

Is there any way to achieve this?

Upvotes: 0

Views: 1401

Answers (2)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

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.

Upvotes: 1

Bond
Bond

Reputation: 16311

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)

Upvotes: 2

Related Questions