0

I'm trying to replace the just first character of a string. Using this answer, I'm able to replace all current characters with the one I want, but what I really need is to only replace the character if it's at the start of a word.


For example, replace c with t:

Original String: Jack is cool
New Sting: Jack is tool


My Current Code:

let aString: String = "jack is cool"
let toArray: Array = aString.componentsSeparatedByString(" ")
let newString: String = aString.stringByReplacingOccurrencesOfString("c", withString: "t", options: NSStringCompareOptions.LiteralSearch, range: nil)

This would print out as:

"jatk is tool"

I assume I have to do something with the range attribute in the newString.

Community
  • 1
  • 1
Micah Cowell
  • 392
  • 4
  • 18

4 Answers4

2

I would use regex. \\b called word boundary which matches between a word character and a non-word character. You may also use negative lookbehind instead of \\b like (?<!\\S)c

var regex:NSRegularExpression = NSRegularExpression(pattern: "\\bc", options: NSRegularExpressionOptions.CaseInsensitive, error: &ierror)!
var modString = regex.stringByReplacingMatchesInString(myString, options: nil, range: NSMakeRange(0, stringlength), withTemplate: "t")
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

var aString = 'jack is cool'; var newString = aString.replace('c','t');

Black Side
  • 17
  • 1
0

var a

var oldString = 'Jack is cool';
var newString = oldString.split(' ');
var x = newString[newString.indexOf('cool')].toString();
x = x.replace('c','t');
newString.splice(newString.indexOf('cool'),1,x);
newString = newString.join(' ').toString();
alert(newString);
Black Side
  • 17
  • 1
0

You can define your range to start and end at the startIndex to make sure it replaces only occurences at the first character of the string:

let coolString = "Cool"
let newString = coolString.stringByReplacingOccurrencesOfString("C", withString: "T", options: [], range: coolString.startIndex...coolString.startIndex)

You can use String method replace() to replace only the first character of a String

var str = "Cool"
str.replaceRange(str.startIndex...str.startIndex, with: "T")
print(str)  // "Tool"

To apply it only to the last word:

var str = "Jack is Cool"
var words = str.componentsSeparatedByString(" ")

if !words.isEmpty {
    if !words[words.count-1].isEmpty {
        words[words.count-1].replaceRange(str.startIndex...str.startIndex, with: "T")
        print( words.last!)  // "Tool\n"
    }
}
let sentence = words.joinWithSeparator(" ")   // "Jack is Tool"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571