1 of 13

CP190-CP0

Topic 7: String

Ninghui Li

Purdue University

2 of 13

ASCII Code

  • ASCII stands for the "American Standard Code for Information Interchange".
  • It was designed in the early 60's, as a standard character set for computers and electronic devices.
  • ASCII is a 7-bit character set containing 128 characters.
  • It contains the numbers from 0-9, the upper and lower case English letters from A to Z, and some special characters.

3 of 13

4 of 13

String Class for Doubles

5 of 13

Abstract Data Type

In computer science, an abstract data type (ADT) is defined by its behavior (semantics) as a number of public methods.

The internal implementation of these methods are hidden.

When using a data type, one needs to be aware of only the public methods.

For example, we use vector is a template abstract data type.

6 of 13

Implement a class with the following public interface

class mystr {

public:

mystr(string s)

mystr(double val, int precision)

double double_val()

vector<mystr> split(const char delim = ' ')

friend ostream& operator<<(ostream& os, const mystr& s);

};

ostream& operator<<(ostream& os, const mystr& s) {

// ...

}

7 of 13

Constructors and member initializer lists

/* creates a new mystr object from a string object */

mystr(string s) : d(s.size()) {

for (int i=0; i<s.size(); i++) d[i] = s[i];

}

/* create a new mystr object that contains string representation

of a double value, with a fixed number of digits after the

decimal point. */

mystr(double val, int precision) : d(1, '0') {

}

8 of 13

Parsing a string into a double

double double_val() {

double res = 0, div = 1;

int idx = 0, len = d.size();

bool neg = false;

if (d[0] == '-') { neg = true; idx++; }

while ('0' <= d[idx] && d[idx] <= '9') {

res = res * 10 + d[idx++] - '0';

}

if (idx < d.size() && d[idx++] == '.') { // has fraction

while ('0' <= d[idx] && d[idx] <= '9') {

res += (d[idx++] - '0') / (div *= 10);

}

}

return neg ? -res : res;

}

9 of 13

Stable Log Rearrange

Try solve it first

See Video and Provided Solution

10 of 13

Example: LeetCode

Find and Replace in String

11 of 13

Solution Code (1)

class Solution {

public:

string findReplaceString(string S, vector<int>& indexes,

vector<string>& sources, vector<string>& targets)

{

vector< pair<int,int> > ops;

for (int i=0; i<indexes.size(); i++)

ops.push_back(make_pair(indexes[i], i));

sort(ops.begin(), ops.end());

string ans; int idx = 0;

12 of 13

for (auto& op : ops) {

int pos = op.first, j = 0, k = op.second;

if (pos > idx) ans.append(S, idx, pos-idx);

idx = pos;

string& p = sources[k], t = targets[k];

for ( ; j<p.length(); j++, pos++) {

if (S[pos] != p[j]) break;

}

if (j == p.length()) { // match

ans.append(t); idx += p.length();

}

}

ans.append(S, idx, S.length()-idx);

return ans;

}

};

13 of 13

End of Topic 7