如何将字符串拆分为数组 [英] How to split a string into arrays

查看:120
本文介绍了如何将字符串拆分为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个输入字符串,例如123456789098765432需要根据位置分成两个数组OddArray和EvenArray,偶数位置(2,4,6,8 ......)的所有数字到EvenArray和所有奇数位(3,5,7 ......)到OddArray的数字



我试过的:



have a input string eg "123456789098765432" need to split into two arrays OddArray and EvenArray based on the positionsi.e, all the digits in even position(2,4,6,8....) to EvenArray and all the digits in oddposition(3,5,7...) to OddArray

What I have tried:

char EvenArray[256],OddArray[256],Inputarray[256];
CString dis = "123456789098765432";
strcpy(Inputarray,dis);
int i,j,k;
int x = strlen(dis);
for(i=0;i<x;i++)>
	{
		if((i+2)%2 ==0)
		{
			
			EvenArray[j]=Inputarray[i];
			j++;
		}
		else
		{
			OddArray[k]=Inputarray[i];
			k++;
		}
	}

推荐答案

嗯...需要稍加调整。

你没有正确处理它 - 你对奇数和偶数的定义不包括零和统一。

零我能理解(它既不奇也不偶)但一个是奇数。 br />
但要排除它们,很简单:更改的初始值

Well... that needs a little tweaking.
You aren't processing it correctly - your definition of "odd" and "even" excludes zero and unity.
Zero I can understand (it's neither odd nor even) but one is odd.
But to exclude them, it's simple: change the initial value of i:
for(i=2;i<x;i++)>

应该这样做。



(请记住,C / C ++ / C#中的数组都是从索引为零的元素开始,而不是索引1:所以在字符串中 12345索引2处的字符为3。

如果您的位置值不允许,您需要稍微调整一下代码。

Should do it.

(Do bear in mind that arrays in C / C++ / C# all start with element at index zero, not index 1: so in the string "12345" the character at index 2 is "3".
If your position values don't allow for that, you need to tweak your code slightly.


这篇关于如何将字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆