Hello forum,
Does swift have String method like this:
syntax:
firstIndex(of: String, at: String.Index) -> String.Index?
usage:
mystring.firstIndex(of: "hello", at: 5)
It allows programmers to find substrings at index.
For example, Ive got text log with some corrupted records like this:
tag xxx tag yyy ta
the first "tag" should be replaced by "tag1", and the second by "tag2" like this:
tag1 xxx tag2 yyy ta
The following is what I will do in C++. How can I do it in Swift?
Thanks
#include <iostream>
#include <string>
using namespace std;
void tag_correct(string &str, string &sub)
{
string::size_type pos = str.find(sub);
if (pos != string::npos)
{
str.replace(pos, sub.size(), "tag1");
}
pos = str.find(sub, pos + 1);
if (pos != string::npos)
{
str.replace(pos, sub.size(), "tag2");
}
}
int main()
{
string str = " tag xxx tag yyy ta";
string sub = "tag";
cout << "old: " << str << endl;
tag_correct(str, sub);
cout << "new: " << str << endl;
}