2013-04-24 126 views
0

我需要创建一个方法,要求用户输入两个单词。一个变量中的第一个单词,另一个变量中的第二个单词。该方案是如下图所示的用户的条目合并: 输入第一个字:树 进入第二个字:计算机 字符串手:TreCom **确保输出是全部大写,从单一的变量结合2个字符串

显示这是我到目前为止(这不是很多):

public static void StringManipulator() 
{ 
String v1,v2; 
c.println("What is the first word?"); 
v1 = c.readLine(); 
c.println("What is the second word?"); 
v2 = c.readLine(); 

你将如何结合2个字符串,以便只有前3个字母显示?

由于

+0

前三每个单词的字母或前三个字母串联的单词?顺便说一句,c的类型是什么? – 2013-04-24 00:15:55

+0

@wickeddreams欢迎来到stackoverflow,如果你发现任何有用的答案,请将它们标记为已接受。 – 2013-04-25 01:06:11

回答

0

提取每个字符串的子串,然后将它们连接起来,例如

// Extract substrings 
String ss1 = v1.substring(0, 3); 
String ss2 = v2.substring(0, 3); 

// Concatenate substrings 
String result = ss1 + ss2; 

// Output in all uppercase 
System.out.println(result.toUpperCase()); 
+0

非常感谢! – Wickeddreams 2013-04-24 00:34:43

0

如果我得到这个权利,你想得到两个单词的输入,然后得到前三个字母,并打印出来?

在这种情况下

尝试以下操作:

String word1 = v1.substring(0,3); 
String word2 = v2.substring(0,3); 
现在

,如果你想简单地打印这两个你只是做:

System.out.println(word1 + " "+word2); 

可以排除之间的空间,以获得1字母字。

0

这种方法将结合前3个字母两个字符串:

String combineWords(String firstWord, String secondWord){ 
firstWord = firstWord.substring(0,2); 
secondWord = secondWord.substring(0,2); 
String combinedWords = firstWord + secondWord; 
return "First word: " + firstWord + ", second word: "+ secondWord + "; Both combined are: " + combinedWords; 
} 

而且你可以使用它像这样:

String v1,v2; 
c.println("What is the first word?"); 
v1 = c.readLine(); 
c.println("What is the second word?"); 
v2 = c.readLine(); 
System.out.println(combineWords(v1, v2));