split the string and add another

Hi All,

I am new to c++, I want to split the string and add some thing to it
for example let say iam getting a input

string old="company$45$0.07$29-09-2009$company2$34$0.09$21-09-2009"

now i want a output where it should come like

string outnew=" ['company',45,0.07,'29-09-2009'],['company2',34,0.09,'21-09-2009'] ";

where i am splitting the string with $ char.

Please help me out.

Thanks in Advance

Regards,

Farooq.
I'm not completely sure what you're asking, " ['company',45,0.07,'29-09-2009'],['company2',34,0.09,'21-09-2009'] " is not very explanatory; are you saying you want the comma's and square brackets?

Look at the string library at these functions:

http://www.cplusplus.com/reference/string/string/find/
http://www.cplusplus.com/reference/string/string/copy/
http://www.cplusplus.com/reference/string/string/substr/
see i will get the input stream form the sql like this "comp1$45$0.07$29-09-2009$comp2$34$0.09$21-09-2009" then i need to separate and concatenate like this " ['company',45,0.07,'29-09-2009'],['company2',34,0.09,'21-09-2009'] " and change that in a particular text file for that format only.

I read the find one it only finds at particular point but my problem is i need to get an array of seperated strings and all the strings should be added with my "['"+string[1]+ "',"+ string[2] +"," +string3 +",' " + string[4] + " '}]"; like this in a for loop and finally the output will be

string output will be string laststr="['company',45,0.07,'29-09-2009'],['company2',34,0.09,'21-09-2009']";

so can you help me please?

I have given you all the references necessary unless I am misunderstanding your problem. Also, use a vector of strings instead of an array. Try and write some code and then post back if you have a problem. All you need to do is find the position at which the '$' occurs then search until you find another '$', and then create a substring manipulating it where necessary e.g. changing 'comp1' to 'company'.
Last edited on
Hello Mcleono,

I tried a sample code


#include <stdafx.h>
#include<string.h>
#include <iostream>
#include <stdio.h>
#include <string>
#include <conio.h>
#include <iostream>

using namespace std;

class Foo{
public:
Foo(int array_size, string nat_string);
~Foo();

void showStringArray(){
int i=0;
int lengthofstring=0;
while(act_string.find("$",posit)!=string::npos)
{
posit= act_string.find("$",posit);
position_array[i]=posit;
++i;
++posit;
}
cout<<"substrings are....";
//in this loop iam getting stack overflow...????
for(j=0;j<size;j++)
{
if(j==0){
substrings_array[j]=act_string.substr(intial,position_array[j]);
intial=position_array[j]+1;
}else{
lengthofstring = position_array[j]-intial;
substrings_array[j]=act_string.substr(intial,lengthofstring);
intial=position_array[j]+1;
}

cout<<substrings_array[j];

}

}

private:
int *position_array;
string *substrings_array;
int size;
string act_string;
int intial,posit,i,j;

};
Foo::Foo(int array_size, std::string nat_string){
intial =0;
posit=0;
j=i=0;
size = array_size;
act_string = nat_string;
position_array = new int[size];
size++;
substrings_array = new string[size];
}
Foo::~Foo(){
delete[ ] position_array;
delete[ ] substrings_array;
}

int main(){
string mystring= "this$123$0.07$29-09-1987$String$789$0.99$29-09-1999";
int position=0,arraysize=1;
while(mystring.find("$",position)!=string::npos){
position = mystring.find("$",position);
arraysize=arraysize+1;
++position;
}
Foo f1(arraysize, mystring);
f1.showStringArray();
scanf("&d",position);
return 0;
}


So i am getting stack overflow in the for loop if j>7 please hlp me out and also i am printing cout<<substrings_array[j];

instead of that i want to do like this

cout<<"['"<<substrings_array[j]<<"',"<<substrings_array[j+1]<<","<<substrings_array[j+2]<<",'"<<substrings_array[j+3]<<"'],";
j=j+3;

I know it wont work but please help me in this as i want the output like ['this',123,0.07,'29-09-1987'],['String',789,0.99,'29-09-1999'];

Thanks in Advance
could you edit that last post and put it in code tags please. Makes it a lot easier to read. eg.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
   string mystring= "this$123$0.07$29-09-1987$String$789$0.99$29-09-1999";
   int position=0,arraysize=1;
   while(mystring.find("$",position)!=string::npos)
   {
      position = mystring.find("$",position);
      arraysize=arraysize+1;
      ++position;
   }
   Foo f1(arraysize, mystring);
   f1.showStringArray();
   scanf("&d",position);
   return 0;
}


Also you shouldn't use conio.h as it is OS specific. It has nothing that your using anyway.

Also you have part class header declaration with your constructor and destructor, but then go on to implement the others. you should just chuck all the declarations at the top near the ctor and dector and then implementations underneath where you have the ctor.
Obviously there's some other problems but that's a start.
Last edited on
What i mean is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

class Foo{
  public:
     Foo(int array_size, string nat_string);
     ~Foo();
     void showStringArray();
     
  private:
     int *position_array;
     string *substrings_array;
     int size;
     string act_string;
     int intial, posit, i, j;
};

Foo::Foo(int array_size, std::string nat_string){
   intial =0;
   // etc ...
   ...
      ...
}

void Foo::showStringArray(){
   int i=0;
   int lengthofstring=0;
   while(act_string.find("$",posit)!=string::npos)
   {
      // ... 
      ...
         ...
}

int main(){ 
   ...
Last edited on
OK, I decided to help you out.

The code I'm going to post is possibly the worst written code ever but it does what is intended by the author of this particular thread.

This code is not in C and you might have to change it a little to conform to the C++ standard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

/*
 * Function: splitStr
 * Arguments: str, the string to be searched. sch, the character to search for
 *                    and lastly the number of strings broken out will be stored in ts.
 *
 * Synopsis: Breaks the string into several pieces. It then returns those pieces
 *                 in a 2 dimensional array (a pointer). Number of strings broken will
 *                 be stored in the 3rd argument. Which may be used for iteration.
 */

char **splitStr(char *str, char sch, size_t *ts)
{
	static char **buff = 0;
	int cntr = 0, nsize = 20, prv = 0, sbcntr = 0;
	static int fncnt = 0;

	if(buff) {
		while(cntr < fncnt) free(buff[cntr++]);
		free(buff);
		cntr = fncnt = 0;
	}

	buff = (char *)malloc(sizeof(char *)*nsize);
	if(!buff) {
		perror("Failed to allocate memory");
		return 0;
	}
	while(str[cntr]) {
		if(str[cntr] == sch) {
			if(fncnt >= nsize) {
				nsize += 10;
				if(realloc(buff, sizeof(char *) * nsize) == NULL) {
					perror("Re-allocation failure");
					return 0;
				}
			}
			buff[fncnt] = (char *)malloc(sizeof(char)*(cntr-prv+1));
			if(buff[fncnt] == NULL) { 
				perror("Seems like we ran out of memory");
				return 0;
			}
			while((buff[fncnt][sbcntr++] = str[prv++]) && (str[prv] != sch && str[prv] != '\0')) ;
			sbcntr = buff[fncnt++][sbcntr] = 0;
			prv += 1;
		}
		cntr++;
	}
	*ts = fncnt;

	return buff;
}

			

main()
{
	char *str = "first$second$third$fourth$";
	char **w;
	char mainstr[80] = "["; /* Make sure it is big enough to hold the above string */
	int cntr = 0;
	size_t total_strs = 0;
	
	w = splitStr(str, '$', &total_strs);
	while(cntr < total_strs) {
		strcat(mainstr, w[cntr++]);
		if(cntr != total_strs) strcat(mainstr, "],[");
	}
	strcat(mainstr, "]");

	puts(mainstr);




	getchar();
	return 0;
}


PS: I know it's too long... and its the worst code ever written in history. So feel free to modify it to your liking. This code currently does exactly what you intend to do. It first searches a string for the '$' and then breaks it, or "spits" it like the topic says. Then I tried to decorate the string with the "],[" which is what the author wanted to do in this case.

I'm still a beginner so please be easy. Any comments are appreciated.
Last edited on
Hello,

Thank u its works fine... but can u tell me if i want to split with string instead of a character then how can i do that..?

string str="Source:Registration \n Table:Calls \n Options: \n Calls::date = Payments::PayDate \n \n Source:Registration \n Table:Employee \n Options: \n Employee::Id = Payments::EmpId";

this is the input string and i want to split the string with "= Payments::"

The output will be like it will splits three string arrays as
splitted_array[1]="Source:Registration \n Table:Calls \n Options: \n Calls::date = ";
splitted_array[2]="PayDate \n \n Source:Registration \n Table:Employee \n Options: \n Employee::Id ";

splitted_array[3]="EmpId";

as i am splitting the string with the string "= Payments::";

its should work just like split() function...
Topic archived. No new replies allowed.