ページ 1 / 1
文字列を変換する
Posted: 2010年10月02日(土) 22:29
by ハト
VC++.netで文字列を出力するプログラムを作っております。
下記の様な文字列を別の決まった雛型に変更したいです。
String^ test = "1 2 3";
例)
"1 2 3" ⇒ "1 - 3"
"10 11 12 13 14 15" ⇒ "10 - 15"
"9 10 11 12" ⇒ "9 - 12"
文字数が2ケタなら前から2文字と後ろから2文字を切り取ってつなげれば出来るのですが
こういう数字だとどうすればいいのかわかりません。
数字と数字の間には必ず半角スペースが空いているのですが
これを使ってSplit等でどうにか出来ないか模索したのですがよくわかりませんでした・・・。
ここはゲームを作る方が多いと思うのですが
わかる方はいらっしゃらないでしょうか?
Re:文字列を変換する
Posted: 2010年10月02日(土) 23:42
by うしお
String^ は、System::Stringであり
C++/CLI言語で、C/C++とは異なる言語ですが、
ここに勘違いはありませんか?
もし勘違いでなければ
これではどうでしょう?
String^ test = "1 2 3";
array<String^>^ SpritedStrArray;
SpritedStrArray = test->Split(' ');
もしC++/CLIではなくC/C++でしたら、
sscanf_s関数などを使用してみてはいかがでしょうか
Re:文字列を変換する
Posted: 2010年10月03日(日) 09:40
by みけCAT
VC++.netはわからないので普通のC言語ですが
#include <stdio.h>
void henkan(char*,char*);
int main(int argc,char* argv[/url]) {
char* taisyou="9 10 11 12";
char result[100];
if(argc>=2) {
henkan(result,argv[1]);
} else {
henkan(result,taisyou);
}
printf("%s\n",result);
return 0;
}
void henkan(char* result,char* source) {
int i;
int last=0;
int output=0;
int status=0;
for(i=0;source!=0;i++) {
if(status==0) {
result[output]=source;
output++;
if(source==' ') {
result[output]='-';
result[output+1]=' ';
output+=2;
last=i+1;
status=1;
}
} else {
if(source==' ')last=i+1;
}
}
for(i=last;source!=0;i++) {
result[output]=source;
output++;
}
result[output]=0;
}
コマンドラインが指定されていない場合は「9 10 11 12」を、
指定されている場合は第一引数を変換します。
Re:文字列を変換する
Posted: 2010年10月03日(日) 10:04
by naohiro19
C++ならBoostライブラリのtokenizerを使えばよいと思います。
Re:文字列を変換する
Posted: 2010年10月03日(日) 14:02
by Justy
先頭と末尾の数字を拾ってきて '-'で繋げるだけなら、Regexでいいんじゃないですか?
String^ test = System::Text::RegularExpressions::Regex::Replace("10 11 12 13 14 15", "^(\\d+)(?:\\s+\\d+)*(\\s+\\d+)$", "$1 - $2");
Re:文字列を変換する
Posted: 2010年10月03日(日) 14:37
by 初級者
その文字列を構成している数値群が連番になっていることは
保証ずみなのでしょうか?
Re:文字列を変換する
Posted: 2010年10月03日(日) 15:06
by みけCAT
No:62612のプログラムにバグがありました。
数字を一つしか入力しなかった場合に変換に失敗します。
#include <stdio.h>
void henkan(char*,char*);
int main(int argc,char* argv[/url]) {
char* taisyou="9 10 11 12";
char result[100];
if(argc>=2) {
henkan(result,argv[1]);
} else {
henkan(result,taisyou);
}
printf("%s\n",result);
return 0;
}
void henkan(char* result,char* source) {
int i;
int last=0;
int output=0;
int status=0;
for(i=0;source!=0;i++) {
if(status==0) {
result[output]=source;
output++;
if(source==' ') {
result[output]='-';
result[output+1]=' ';
output+=2;
last=i+1;
status=1;
}
} else {
if(source==' ')last=i+1;
}
}
if(last==0) {
result[output]=' ';
result[output+1]='-';
result[output+2]=' ';
output+=3;
}
for(i=last;source!=0;i++) {
result[output]=source;
output++;
}
result[output]=0;
}